getPrototypeOf()
Summary
The getPrototypeOf() trap
"returns the prototype (i.e. the value of the
internal [[Prototype]] property) of the specified
object."
Examples
In JavaScript, it's very common to have a constructor function with
methods defined on the prototype property of the function:
function Rectangle(width, height) {
this.width = width;
this.height = height;
}
Rectangle.prototype.getArea = function() {
return this.width * this.height;
};
var r = new Rectangle(3, 4);
r.getArea(); // returns 12
The prototype of r in this case is Rectangle.prototype.
Reflect.getPrototypeOf(r) === Rectangle.prototype;
// returns true
The getArea() method is available to the r
object because it inherits from
Rectangle.prototype.
Usage in es7-membrane
I do not recommend disabling the getPrototypeOf() trap, because
prototypes are central to the normal operation of JavaScript.
Currently, it throws an exception when disabled.
Coming soon
When the getPrototypeOf() trap is disabled, it will return null to indicate there is no prototype available.
Reflect.getPrototypeOf()
by
Mozilla Contributors
is licensed under
CC-BY-SA 2.5
.
setPrototypeOf()
Summary
The setPrototypeOf() trap
"sets the prototype (i.e., the internal
[[Prototype]] property) of a specified object to
another object or to null."
Examples
In JavaScript, it's very common to have a constructor function with
methods defined on the prototype property of the function:
function Rectangle(width, height) {
this.width = width;
this.height = height;
}
Rectangle.prototype.getArea = function() {
return this.width * this.height;
};
var r = new Rectangle(3, 4);
r.getArea(); // returns 12
The prototype of r in this case is Rectangle.prototype.
The getArea() method is available to the r
object because it inherits from Rectangle.prototype.
Setting the prototype means altering all the inherited
properties of the object you're inspecting:
function Rectangle(width, height) {
this.width = width;
this.height = height;
}
Rectangle.prototype.getArea = function() {
return this.width * this.height;
};
var r = new Rectangle(3, 4);
const newProto = {
getPerimeter: function() {
return (this.width + this.height) * 2;
}
};
Reflect.setPrototypeOf(r, newProto);
r.getPerimeter(); // returns 14;
try {
r.getArea(); // throws TypeError: r.getArea is not a function
}
catch (e) {
// do nothing
}
Reflect.setPrototypeOf(newProto, Rectangle.prototype);
r.getArea(); // returns 12
Usage in es7-membrane
I strongly recommend disabling the setPrototypeOf() trap, because
anyone who sets a prototype on your objects effectively owns all the
inherited properties of your objects. For this reason, the
setPrototypeOf() trap is not checked by default.
Reflect.setPrototypeOf()
by
Mozilla Contributors
is licensed under
CC-BY-SA 2.5
.