如构造函数中的所示
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
相关文章:
- ES6构造函数返回基类的实例
- 使用Google Visualization动态调用构造函数
- javascript中对象构造函数中的var属性与this.properties
- 理解typescript中的构造函数接口
- 为什么构造函数不是构造函数
- 如果在构造函数中有“返回”,则在 JavaScript 中的新运算符中做了什么
- 拦截对构造函数的调用
- 使用闭包共享构造函数参数
- 文本表示法VS.构造函数,用于在JavaScript中创建对象
- 从js引擎的角度来看闭包和构造函数是如何工作的
- 如何使用此从对象访问构造函数
- Javascript:为什么是构造函数's __proto__属性Empty(){}
- 当一个重要的构造函数参数丢失时应该发生什么
- Chrome Javascript日期构造函数错误
- 如何使用构造函数's的输出,以便将值插入到对象中
- 为什么在调用父构造函数时在[]中发送数据
- 构造函数函数闭包变量
- ES6类是否与构造函数相同
- 构造函数中的事件处理程序与构造函数外的事件处理函数的行为不同
- 如果在构造函数内部为else,则Javascript是可选的