简体   繁体   English

在javascript中访问父属性

[英]Accessing parent property in javascript

I'm new to JS and have a question about inheritance. 我是JS的新手,对继承有疑问。 How are inherited properties accessed through the child class? 如何通过子类访问继承的属性?

Lets say I have the following classes: 假设我有以下课程:

function ParentClass(parentArg) {
    this.parentProperty = parentArg;
}

function ChildClass(childArg1, childArg2) {
    this.prototype = new ParentClass(childArg1);
    this.childProperty = childArg2;
}

And at some point an object is created of ChildClass, like so: 在某些时候,对象是由ChildClass创建的,如下所示:

var foo = new ChildClass('value 1', 'value 2');

Then how can a parent property be accessed from the instance of the child? 那么如何从子实例访问父属性? The following returns 'undefined'. 以下内容返回'undefined'。

var parentValue = foo.parentProperty;

Much appreciated. 非常感激。 Cheers 干杯

If you want to initialize the parentProperty , you have to do it like this 如果要初始化parentProperty ,则必须这样做

function ParentClass(parentArg) {
    this.parentProperty = parentArg;
}

function ChildClass(childArg1, childArg2) {
    ParentClass.call(this, childArg1);
    this.childProperty = childArg2;
}

And to actually inherit Parent't methods, you might want to do 要实际继承Parent't方法,您可能想要这样做

ChildClass.prototype = Object.create(ParentClass.prototype);

After making these changes, 进行这些更改后,

var foo = new ChildClass('value 1', 'value 2');
console.log(foo);
# { parentProperty: 'value 1', childProperty: 'value 2' }

foo.prototype.parentProperty如果你想获得value 1

The problem is because you can't assign to a prototype property before the object definition is declared: 问题是因为在声明对象定义之前无法分配给prototype属性:

Doesn't work: 不起作用:

function Parent() {
    this.parentProperty = "test";
}

function Child() {
  // This doesn't work because the prototype is set inside of the definition
  this.prototype = new Parent();
}

var child = new Child();
alert(child.parentProperty);

Works 作品

function Parent() {
    this.parentProperty = "test";
}

function Child() {
    // Define prototype outside of function constructor
}
Child.prototype = new Parent();

var child = new Child();    
alert(child.parentProperty);

Also notice that in the second example we assign to Child.prototype and not new Child().prototype 另请注意,在第二个示例中,我们分配给Child.prototype而不是新的Child()。原型

For ES6, you use extends, eg 对于ES6,您使用extends,例如

class A { prop = "prop" } 
class B extends A{} 
new B();

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM