繁体   English   中英

从这里访问原型功能

[英]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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM