如何为对象原型的属性建立原型?

时间:2015-09-23 18:06:00

标签: javascript node.js properties prototype

我想完成以下操作,以便我可以原型化对象原型的属性。这很难解释,所以用一些代码可以很好地说明。以下代码在控制台中为this.name提供了未定义的内容。这是由于绑定失败。但是我怎么能这样做,以便按预期工作:

var User = function(name) {
    this.name = name;
};

User.prototype.actions = {};

User.prototype.actions.eats = function(what) {
    console.log(this.name + ' eats ' + what);
};

User.prototype.actions.eats = function(what) {
    console.log(this.name + ' eats ' + what);
};

var Member = function(name) {
    User.call(this,name);
};

Member.prototype = Object.create(User.prototype);
Member.prototype.constructor = Member;

Member.prototype.actions.sleeps = function(time) {
    console.log(this.name + ' sleeps ' + time);
}

var user = new User('john');
var member = new Member('steward');

user.actions.eats('fries');

member.actions.eats('potatoes');
member.actions.sleeps('3 hours');

0 个答案:

没有答案