Reputation: 71
I want stop inheriting a certain property from the parent object. How can I achieve that through inheritance in Javascript?
Here's an example:
var fun1 = function () {
this.name = "xxx";
this.privatenumber = 98765432100;
}
fun1.prototype.f = "yyy";
var obj1 = new fun1();
var fun2 = function () {}
fun2.prototype = Object.create(obj1);
var obj2 = new fun2();
In this example I don't want to inherit the privatenumber
property to child.
Upvotes: 0
Views: 1170
Reputation: 288600
A simple way is overriding it with undefined
:
fun2.prototype = Object.create(obj1);
fun2.prototype.privatenumber = undefined;
var obj2 = new fun2();
obj2.privatenumber; // undefined
Note that "privatenumber" in obj2
will still return true
.
Upvotes: 0
Reputation: 66364
Don't use instances in the prototype chain, inherit directly from the prototype.
If the instance with the inheritance should be constructed by the other constructor too, tell it so
function Fun1() {
this.name = "xxx";
this.privatenumber = 98765432100;
}
Fun1.prototype.f = "yyy";
function Fun2() {
// if instances of Fun2 should be constructed by Fun1 then
Fun1.call(this);
// and if you still don't want `privatenumber` which is now an own property, delete it
delete this.privatenumber;
}
Fun2.prototype = Object.create(Fun1.prototype);
Now look at what we have;
var foo = new Fun2(); // Fun2 own `{name: "xxx"}`, inherting `{f: "yyy"}`
'privatenumber' in foo; // false
Upvotes: 1