如何解决将原型设置为父级:Call() 和 New 运算符之间的区别
众所周知,有两种方法可以调用构造函数并将 this
设置为对象:
- 使用
new
运算符 ->new ConstructorFn();
- 使用
call
方法 ->ConstructorFn.call(this);
在创建对象实例时都可以正常工作,但 call()
无法将子原型设置为父原型。看下面的代码:
HtmlInputElement.prototype = HtmlElement.call(this); // sets prototype to undefined
HtmlInputElement.prototype = new HtmlElement(); // works fine
完整代码:
'use strict'
function HtmlElement(selector) {
this.selector = selector;
}
HtmlElement.prototype = {
constructor: HtmlElement,selectElement: function() {
return document.querySelector(this.selector);
}
}
function HtmlInputElement(selector) {
HtmlElement.call(this,selector);
}
HtmlInputElement.prototype = HtmlElement.call(this);
HtmlInputElement.prototype.constructor = HtmlInputElement;
const input = new HtmlInputElement('#name-input');
input.selectElement(); // Error! input.selectElement is not a function!
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。