我想停止从父对象继承某个属性。如何通过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属性继承给child。

最佳答案

不要在原型链中使用实例,而是直接从原型继承。

如果具有继承关系的实例也应该由其他构造函数构造,请告诉它

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

关于javascript - 如何停止继承JavaScript中父对象的某些属性,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/31978617/

10-09 18:11