JavaScript - 继承多个实例之间的属性

时间:2017-11-28 11:44:08

标签: javascript object properties instance

我很难理解在多个实例属性/方法之间共享的方式。

我知道可以通过创建实例的新对象Object.create()来继承属性。但它创建了一个不能在多个(子)实例之间共享的新对象。

我的目标是创建一个包含属性和辅助方法的Parent函数。这些属性/方法应该在子函数之间共享。当子(或父)方法修改属性时,它应该可以访问并反映在所有实例(父/子)中。

如何实现这样的行为?

这是一个经典继承的例子(这不是我想要的),但说明了我想要实现的原则:

// File 1 - Parent
var Parent = function() {
    this.var1 = 'var1';
    this.var2 = 'var2';
};

Parent.prototype.setVar = function( name, arg ) {
    this[name] = arg
};

Parent.prototype.getVar = function( name ) {
    return this[name];
};

// File 2 - Child 1
var Child1 = function() {
    Parent.call( this );
};

Child1.prototype = Object.create( Parent.prototype );
Child1.prototype.constructor = Child1;

Child1.prototype.print = function() {
    this.setVar( 'var1', 'test var 1' );
    this.setVar( 'var2', 'test var 2' );
    console.log( this.var1, this.var2 )
};

// File 3 - Child 2
var Child2 = function() {
    Parent.call( this );
};

Child2.prototype = Object.create( Parent.prototype );
Child2.prototype.constructor = Child2;

Child2.prototype.print = function() {
    console.log(this.var1, this.var2)
};

var Child1 = new Child1();
var Child2 = new Child2();
Child1.print(); // test var 1 test var 2
Child2.print(); // var1 var2

/*** => How to share/inherit the variables from Parent in all children (Child1, Child2, etc...)
Child1.print(); // test var 1 test var 2
Child2.print(); // test var 1 test var 2
***/

小提琴:https://jsfiddle.net/guL2ahpq/

也许我对我正在寻找的概念非常了解。 我希望有人能够以一种简单的方式解释如何实现我正在寻找的东西。我想我在OOP中缺乏一些知识......

1 个答案:

答案 0 :(得分:1)

您可以在Parent的原型对象上设置所有实例继承的变量:

function Parent() {}
Parent.prototype.var1 = 'var1';
Parent.prototype.var2 = 'var2';
Parent.prototype.setVar = function(name, arg) {
    Parent.prototype[name] = arg
};

当然这是一种很少使用的模式,会导致很多混乱。不要在实例上放置可变共享属性。您可以通过简单地使用全局变量或Parent的静态属性来实现相同目的。

相关问题