我想停止从父对象继承某个属性。如何通过Javascript中的继承实现这一目标?
以下是一个例子:
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();
在此示例中,我不想将privatenumber
属性继承到子级。
答案 0 :(得分:1)
不要在原型链中使用实例,直接从原型继承。
如果具有继承的实例也应该由其他构造函数构造,那么告诉它
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);
现在看看我们有什么;
var foo = new Fun2(); // Fun2 own `{name: "xxx"}`, inherting `{f: "yyy"}`
'privatenumber' in foo; // false
答案 1 :(得分:0)
一种简单的方法是用undefined
覆盖它:
fun2.prototype = Object.create(obj1);
fun2.prototype.privatenumber = undefined;
var obj2 = new fun2();
obj2.privatenumber; // undefined
请注意,"privatenumber" in obj2
仍会返回true
。