gpt4 book ai didi

javascript - javascript 中的继承不起作用

转载 作者:行者123 更新时间:2023-11-28 20:15:54 25 4
gpt4 key购买 nike

为什么jordan没有Human类的属性?难道说 Coder.prototype = new Human; 就足以让所有 Coder 类继承 Human 类的所有属性吗?

这与将函数定义为赋值有什么关系吗?

var Human = function() {
var hi = function() {
alert('hi');
};
return {
name : 'dan',
sayHi : hi
};
};

var dan = new Human();

var Coder = function() {
var code = function() {
alert('1010101');
};
return {
code : code
};
};

Coder.prototype = new Human;
Coder.prototype.constructor = new Coder;
var jordan = new Coder();
console.log(jordan);

最佳答案

您的构造函数不会返回它们正在创建的对象,因此继承不起作用。改用这个:

var Human = function() {
this.sayHi = function() {
alert('hi');
};
this.name = 'dan';
};

var dan = new Human();

var Coder = function() {
this.code = function() {
alert('1010101');
};
};

Coder.prototype = new Human;
Coder.prototype.constructor = Coder;
var jordan = new Coder();
console.log(jordan);

另一种选择,将内容从 Human 移至原型(prototype):

var Human = function() {};
Human.prototype.sayHi = function() {
alert('hi');
};
Human.prototype.name = 'dan'; // will be shadowed if redefined on instances

var Coder = function() {};
Coder.prototype = Object.create(Human.prototype);
Coder.prototype.code = function() {
alert('1010101');
};
var jordan = new Coder();
console.log(jordan);

Object.create 的 polyfill 是 available on MDN

关于javascript - javascript 中的继承不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19189092/

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