如以下代码,User 之中应该包含 VIPUser 但是VIPUser却用不了User的sayHello 方法,
function User(firstName, lastName, age) {
this.firstName = firstName;
this.lastName = lastName;
this.age = age;
this.fullName = this.firstName + " " + this.lastName;
}
User.prototype.sayHello = function() {
console.log(`大家好,我叫${this.fullName},今年${this.age}岁了`);
}
function VIPUser(firstName, lastName, age, money) {
User.call(this, firstName, lastName, age);
this.money = money;
}
VIPUser.prototype.upgrade = function() {
console.log(`使用了${100}元软妹币,升级了!`);
this.money -= 100;
}
var vUser = new VIPUser("姬", "成", 1, 100);
</script>
它们原型链如下图
如何让 vUser也可以是使用 User的方法呢
function User(firstName, lastName, age) {
this.firstName = firstName;
this.lastName = lastName;
this.age = age;
this.fullName = this.firstName + " " + this.lastName;
}
User.prototype.sayHello = function () {
console.log(`大家好,我叫${this.fullName},今年${this.age}岁了`);
}
function VIPUser(firstName, lastName, age, money) {
User.call(this, firstName, lastName, age);
this.money = money;
}
myplugin.inherit(VIPUser , User)
VIPUser.prototype.upgrade = function () {
console.log(`使用了${100}元软妹币,升级了!`);
this.money -= 100;
}
var vUser = new VIPUser("姬", "成", 1, 100);
// 继承 es5的方法 圣杯
if (!this.myplugin) {
this.myplugin = {};
}
this.myplugin.inherit = function (son, father) {
son.prototype = Object.create(father.prototype);//create/es5 创建一个新对象,其隐式原型指向father.prototype
son.prototype.constructor = son;
son.prototype.usber = father.prototype
}
原型链如下
老版本的方法 圣杯
this.myplugin.inherit = function (son, father) {
// 之前的写法 圣杯模式
function Temp() { };
Temp.prototype = father.prototype;
son.prototype = new Temp();
son.prototype.constructor = son;
son.prototype.usber = father.prototype;
// 高级简化版
(function () {
function Temp() { };
return function (son, father) {
Temp.prototype = father.prototype;
son.prototype = new Temp();
son.prototype.constructor = son;
son.prototype.usber = father.prototype
}
})(son, father)
}
原型链如下