[英]access prototype function from this
我正在尝试修复一些使用函数和原型函数的Javascript。 由于某种原因,当我尝试访问原型函数时, 总是无法定义原型函数,因此我无法弄清原因。
这是我正在尝试做的一个简单示例。 基本上,我想使用this
从原始Container
函数声明中引用_open
原型。
Container();
function Container() {
alert(this._open);
}
Container.prototype._open = function() {
alert("hey");
}
三件事:
new Container();
代替Container();
。 new Container();
所有prototype
增加之后的生产线。 this._open();
而不是alert(this._open);
实际执行功能。 因此,您的代码应如下所示:
function Container() {
this._open();
}
Container.prototype._open = function() {
alert('open');
}
new Container();
希望这可以帮助。
function Container() {
this._open();
}
Container.prototype._open = function() {
alert("hey");
}
var container = new Container();
尝试以上。 您需要使用new
创建对象的实例。 否则, this
引用的是全局对象,而不是原型成员。
使用没有new()的构造函数会导致奇怪的错误。 因为this
将引用全局对象===窗口。
在定义之后并使用new
评估程序调用Container()
: var instace = new Container();
function Container() { this._open(); } Container.prototype._open = function(e) { alert("hey"); } var instance = new Container();
也许您不需要两个警报。
您的代码利用了提升(可能是无意间)的优势。 因此, 看起来原型是在执行之前构建的,但实际上并非如此。
这就是您的代码实际的样子
function Container(){
alert(this._open);
}//functions are "hoisted"
Container();
Container.prototype._open = function() {
alert("hey");
}
见到这种情景,很显然,当Container()
被调用,即转让的原型还没有发生。 不仅如此,还像函数一样调用Container()
而不是实例化 。 当像函数一样调用Container
时,发生的情况是this
绑定没有发生。 最终结果是, this
采用了全局引用(假设脚本不在严格模式下)。 此时的全局引用没有对_open
属性的引用,因此将发出undefined
的警报,并且仅此而已。
为了._open
实际警告功能_open,如在此定义的,将是在实例化之前首先将属性._open
分配给Container
的原型。 否则,该属性将在创建的对象中不存在。
接下来,实例化必须与new
关键字一起使用。 这将调用函数构造函数,设置它自己的执行上下文,该上下文带有ThisBinding
和一些变量环境。
总而言之,看起来像这样
//place the definition at the top for readability
//so it is obvious that it is declared first
function Container(){
alert(this._open);
}
//Next ensure that the _open property is defined on the prototype before
//instantiating the object
Container.prototype._open = function() {
alert("hey");
}
//Lastly, ensure that the keyword `new` is used to start the
//process of instantiation
new Container();
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.