使用构造函数函数的Javascript继承
Javascript Inheritance using constructor functions
我正试图使一个构造函数成为另一个构造函数的父函数。
function Fruit() {
this.isEatable = function() {
return eatable;
};
}
function Apple(eatable , sweet) {
this.isSweet = function() {
return sweet;
};
var instance = {};
Fruit.apply(instance);
_.extend(this, instance);
}
var a = new Apple(true, false);
console.log(a.isEatable()); // Uncaught ReferenceError: eatable is not defined
但正如你所看到的,我犯了一个错误,原因是什么?让一个函数从另一个函数继承的更好方法是什么?
我也尝试了以下操作,但仍然得到相同的错误:
function Fruit() {
this.isEatable = function() {
return eatable;
};
}
function Apple(eatable , sweet) {
this.isSweet = function() {
return sweet;
};
}
_.extend(Apple.prototype , Fruit.prototype);// I use lodash library
var a = new Apple(true, false);
console.log(a.isEatable()); // Uncaught ReferenceError: eatable is not defined
尝试以下
function Fruit(eatable) {
this.eatable = eatable;
this.isEatable = function() {
return this.eatable;
};
}
function Apple(eatable , sweet) {
// Call the constructor of the inherited 'object'
Fruit.call(this, eatable);
this.sweet = sweet;
this.isSweet = function() {
return this.sweet;
};
}
// Inherit the Fruit.prototype methods for Apple
Apple.prototype = Object.create(Fruit.prototype);
var a = new Apple(true, false);
console.log(a.isEatable());
这是基于MDN Object.create文档中作为示例给出的(非常有用)代码。这是一个JSFiddle。
其他方式
function Fruit() {
this.isEatable = function() {
return this.eatable;
};
}
function Apple(eatable , sweet) {
this.sweet=sweet;
this.eatable=eatable;
this.isSweet = function() {
return this.sweet;
};
this.prototype= Fruit.apply(this);
}
var a = new Apple(true, false);
console.log(a.isEatable());
这和@Asryael有点像,我想
简短的解释:prototype将新的Fruit对象与Apple的this
绑定,因此您不需要在根对象中再次传递参数,this
会处理它。
相关文章:
- 关于Javascript继承,我可以'我不明白
- Javascript继承代码集
- Javascript:继承原型而不重新定义构造函数
- JavaScript继承:未捕获的范围错误:超过了最大调用堆栈大小
- JavaScript继承:为什么从实例复制
- javascript继承中正确的原型做作是什么
- 没有原型的Javascript继承
- Javascript继承-使用.call方法
- 运行Javascript继承代码时出错
- Javascript继承构造函数
- Javascript继承和封装,高效完成
- 具有简洁原型赋值语法的Javascript继承
- Javascript继承的问题&基类原型
- JavaScript继承构造函数.prototype
- javascript继承说明
- Javascript继承:从超类的方法设置子类的属性
- 简单的 Javascript 继承示例
- 具有意外行为的 JavaScript 继承
- 基于实例的 JavaScript 继承
- 为什么 JavaScript 继承是这样工作的