如构造函数中的所示

As indicated by this in the constructor

本文关键字:构造函数      更新时间:2023-09-26

有以下代码:

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('Иван', 'Горемыко');

在这里,我们在 this 的上下文中调用用户。如(参考)所示,在这种情况下?我知道创建了一个新对象。

User.call(this, firstName, surName);

我想了解在User.call(this)中传递的内容是什么?

创建继承类的最佳方法是:

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