简体   繁体   中英

Accessing parent property in javascript

I'm new to JS and have a question about inheritance. 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:

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'.

var parentValue = foo.parentProperty;

Much appreciated. Cheers

If you want to initialize the parentProperty , you have to do it like this

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

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:

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

For ES6, you use extends, eg

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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