function Singer(g) {
this.genre = g;
this.rock = function() {
console.log("ROCK");
}
}
Singer.prototype.sing = function() {
console.log(this.genre);
}
function metalSinger() {
}
metalSinger.prototype = Singer.prototype
var james = new metalSinger();
console.log(james.sing())
metalSinger对象仅继承了Singer对象的原型(prototype)函数。如何继承 Singer 的变量(this.genre)和函数(this.rock)?
最佳答案
您可以使用带有继承的类模式。
https://developer.mozilla.org/en-US/docs/Learn/JavaScript/Objects/Inheritance
function Singer(g) {
this.genre = g;
this.rock = function() {
console.log("ROCK");
}
}
Singer.prototype.sing = function() {
console.log(this.genre);
}
function MetalSinger(g) {
Singer.call(this, g);
}
var ms = new MetalSinger("foo");
console.log(ms.rock());
关于javascript - JavaScript中如何继承变量?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44819484/