我有以下代码并且遇到了调用和prototype.constructor方法但是没有足够的知识来使它们正常工作。有人可以填写我所缺少的知识。管理员是用户。
function User(user) {
this.id = user.id;
this.email = user.email;
this.firstname = user.firstname;
this.lastname = user.lastname;
this.age = user.age;
}
User.prototype.fullName = function(){
return this.firstname + ' ' + this.lastname
}
function Admin(admin){
this.writer = admin.writer;
this.editor = admin.editor;
this.publisher = admin.publisher;
//User.call(this);
}
Admin.prototype.fullAccess = function(){
return (this.writer && this.editor && this.publisher);
}
//Admin.prototype = new User();
//Admin.prototype.constructor = Admin;
var user1 = new User({
'id': 1,
'email': 'sd_brown@ntlworld.com',
'firstname': 'Stephen',
'lastname': 'Brown',
'age': 44
});
var user2 = new User({
'id': 2,
'email': 'johndoe@ntlworld.com',
'firstname': 'John',
'lastname': 'Doe',
'age': 25
});
var admin1 = new Admin({
'writer': true,
'editor': true,
'publisher': true,
});
var admin2 = new Admin({
'writer': true,
'editor': true,
'publisher': false,
});
答案 0 :(得分:2)
你几乎就在那里,只需要做一些简单的改动:
User.call(this);
更改为User.call(this, admin);
。这会将传递给Admin构造函数的参数传递给“super”构造函数。Admin.prototype = new User();
更改为Admin.prototype = new User({});
(传递一个空对象,否则用户构造函数将尝试访问未定义的属性时抛出错误)。或者只使用Admin.prototype = Object.create(User.prototype);
(IE< = 8所需的polyfill)。