Javascript 继承类中的局部属性/变量

Javascript 继承类中的局部属性/变量,javascript,variables,inheritance,local,Javascript,Variables,Inheritance,Local,我有一组从基类派生的类,如下所示(例如): 我想向基类中添加变量(不是类似Java静态的变量,而是每个类实例具有单独值的变量)。然而,我希望派生的类也能够访问它们 我不是Javascript专家,我已经玩了一点,但我不能让它工作。这有可能实现吗?还是应该实现setter和getter?示例: function Base( name ){ this.name = name; } function Derived( name, type ) { Base.call( this,

我有一组从基类派生的类,如下所示(例如):

我想向基类中添加变量(不是类似Java静态的变量,而是每个类实例具有单独值的变量)。然而,我希望
派生的
类也能够访问它们

我不是Javascript专家,我已经玩了一点,但我不能让它工作。这有可能实现吗?还是应该实现setter和getter?

示例:

function Base( name ){
    this.name = name;
}


function Derived( name, type ) {
    Base.call( this, name );
    this.type = type;
}
Derived.prototype = Object.create( Base.prototype );


var b = new Base( 'Peter' );
var d = new Derived( 'John', 2 );
因此,
Base
类定义了一个实例成员--
'name'
派生的
类定义了一个额外的实例成员-
“type”

关键部分是在
派生的
构造函数调用中调用
构造函数-因此,在内部,您“设置”实例,就像它是
实例一样(您传入所需的参数),然后,使用仅为
派生的
实例定义的附加内容来扩充实例


因此,在我上面的例子中,
b
有一个自己的属性-
'name'
,而
d
有两个自己的属性-
'name'
,和
'type'

您应该实现不标记标题,ta:)值得注意的是Object.create是ES5,虽然为较旧的实现提供了解决方案。@RobG认为polyfill很好,但最简单的解决方案当然是只为
IE lt 9
包含ES5垫片。(它还包括一个。)
function Base( name ){
    this.name = name;
}


function Derived( name, type ) {
    Base.call( this, name );
    this.type = type;
}
Derived.prototype = Object.create( Base.prototype );


var b = new Base( 'Peter' );
var d = new Derived( 'John', 2 );