gpt4 book ai didi

Javascript调用基类构造函数

转载 作者:行者123 更新时间:2023-11-28 18:48:57 25 4
gpt4 key购买 nike

Person 是基类,Emp 继承自 Person。我正在尝试在 Emp 中使用 Personnamelocation 属性。

function Person(name, location){
this.name = name;
this.location = location;
}

Person.prototype.getName = function(){
return 'Name: ' + this.name;
}

function Emp(id, name, location){
this.id = id;
Person.call(this, name);
Person.call(this, location);
}

Emp.prototype = Object.create(Person.prototype);

var e1 = new Emp(1, 'John', 'London');
e1.id // 1
e1.name // 'London'
e1.location //undefined

是什么原因导致此错误以及为什么名称采用伦敦值?

最佳答案

为什么使用一个参数调用构造函数两次?

function Emp(id, name, location){
this.id = id;
Person.call(this, name, location);
}

关于Javascript调用基类构造函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34821077/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com