理解Javascript构造函数:自定义create方法
Understanding Javascript constructors: custom create method
我试图更好地理解Javascript中的OOP。有人能解释一下在下面的例子中如何使用create方法和替代方法吗?我在网上查了一下,看了几篇关于SO的文章,仍然没有完全掌握下面代码中发生了什么。我提供了一些评论来说明我的理解。请纠正我的错误。
这个例子用于覆盖基类中的方法:
// Defines an Employee Class
function Employee() {}
// Adds a PayEmployee method to Employee
Employee.prototype.PayEmployee = function() {
alert('Hi there!');
}
// Defines a Consultant Class and
// Invokes the Employee Class and assigns Consultant to 'this' -- not sure and not sure why
// I believe this is a way to inherit from Employee?
function Consultant() {
Employee.call(this);
}
// Assigns the Consultant Class its own Constructor for future use -- not sure
Consultant.prototype.constructor = Consultant.create;
// Overrides the PayEmployee method for future use of Consultant Class
Consultant.prototype.PayEmployee = function() {
alert('Pay Consultant');
}
代码:
function Consultant() {
Employee.call(this);
}
在调用Consultant构造函数时调用Employee构造函数(即,在创建Consultant实例时)。如果Employee构造函数正在进行任何类型的初始化,那么在创建顾问"子类型"时调用它将是很重要的。
这个代码:Consultant.prototype.constructor = Consultant.create;
有点神秘。它暗示有一个名为create的函数,它是Consultant函数对象的属性。但是,在您发布的代码示例中,没有这样的属性。实际上,这一行是将undefined
赋值给Consultant构造函数。
你的问题没有问,但只是供参考,我认为你可能想要的是而不是那行与create函数,是这样的:
Consultant.prototype = new Employee();
Consultant.prototype.constructor = Consultant;
这是原型继承模式。这当然不是唯一或最好的方法,但我喜欢它。
如果Employee接受一个参数,你可以这样处理:
// Employee constructor
function Employee(name) {
// Note, name might be undefined. Don't assume otherwise.
this.name = name;
}
// Consultant constructor
function Consultant(name) {
Employee.call(this, name);
}
// Consultant inherits all of the Employee object's methods.
Consultant.prototype = new Employee();
Consultant.prototype.constructor = Consultant;
相关文章:
- electronic BrowserWindow的最小高度和宽度在hide()show()方法之后不起作用
- 有没有任何方法可以将控制器从文件加载到ui路由器$stateProvider中
- javascript中的Object.create方法
- 重写JavaScript中的Object.create方法
- 级联下拉列表mvc3,create方法
- NodeJS - 猫鼬,subdoc 对象没有方法 .id() 或 .create()
- 圣经般的"Sortable.create()"方法在进行AJAX调用以更新无序列表后不起作用
- ES6方法没有在create-react-app中定义
- 没有new关键字或.create方法的对象()
- 是否可以将javascript变量发送到控制器的create方法?
- AJAX错误400错误请求-需要将参数从一个方法传递到同一控制器的create方法
- JavaScript无法在object.create(baseObject)之后访问相同的对象方法
- Uncaught TypeError: Object [Object Object]没有方法'create
- 如何在rails控制器中为create方法呈现javavscript文件
- Laravel foreach的create方法将只添加一条记录
- 为什么Backbone's collection create()方法未填充id
- 当作为 Web 应用程序运行时,对象不支持 IE11 上的属性或方法“create”,在浏览器中直接打开 HTML 时很
- 使用Object.create(),范例应该将方法附加到它们的'prototype'财产
- Javascript在Object Literal方法中直接调用方法和使用Object.create方法的区别
- 理解Javascript构造函数:自定义create方法