拥有以下代码:
function AdminUser(firstName, surName) {
User.call(this, firstName, surName);
this.edit = function() {
alert('test password');
}
}
function User(firstName, surName) {
this.firstName = firstName;
this.surName = surName;
this.sayHi = function() {
alert(this.firstName + ' : ' + this.surName);
}
}
var user = new User('Василий', 'Пупкин');
var admin = new AdminUser('Иван', 'Горемыко');
这里我们在此上下文中调用User。在这种情况下如(引用)所示?我知道创建了一个新对象。
User.call(this, firstName, surName);
我想了解User.call(this)中传递的是什么?
答案 0 :(得分:1)
创建继承类的最佳方法是:
function User(firstName, surName){
// Make assigment to properties.
this.firstName = firstName;
this.surName = surName;
};
// Declare default properties values:
User.prototype.firstName = '';//Set to empty string or whatever you need.
User.prototype.surName = '';//Set to empty string or whatever you need.
//Export functions to prototype.
User.prototype.sayHi = function(){/* Some code */};
function AdminUser(firstName, surName){
//Call parent class constructor
User.call(this, firstName, surName);
//Add addition logic here.
};
//Make prototype inheritance.
AdminUser.prototype = Object.create(User.prototype);
AdminUser.prototype.edit = function(){/* Some code */};
现在,您的AdminUser
继承自User
课程,您可以进行检查:
var au = new AdminUser('Name','SurName');
console.log(au instanceOf User); //true
console.log(au instanceOf AdminUser); //true