gpt4 book ai didi

Javascript 不继承原型(prototype)属性

转载 作者:行者123 更新时间:2023-11-29 18:12:47 25 4
gpt4 key购买 nike

为什么 Javascript 不继承原型(prototype)的属性

示例

function Man(name,age,color){
this.name = name;
this.age = age;
this.color = color;
}

boy = function Boy(){};

boy.prototype = new Man();

myboy = new boy('hari',14,'blue');

console.log(myboy);
// => myboy {name:undefined, age:undefined, color:undefined}

它不继承属性。

它意味着具有属性

// => myboy {name:'hari', age:14, color:'blue'}

最佳答案

It does not inherit the properties.

是的,它显然有 nameagecolor。它们只是没有任何值,因为您调用 Man 时没有任何参数,而 Boy 不会对您提供的参数执行任何操作。

您的继承设置完全不正确。您应该使用 Object.create 将父原型(prototype)添加到子原型(prototype)链中:

Boy.prototype = Object.create(
Man.prototype,
{constructor: {value: Boy, writable: true}}
);

并且,与其他语言一样,您必须在子构造函数(应用于新的子实例)中调用父构造函数,传递所有需要的参数:

function Boy(name, age, color) {
Man.call(this, name, age, color);
}
// or
function Boy() {
Man.apply(this, arguments);
}

更多信息:

关于Javascript 不继承原型(prototype)属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25812342/

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