从这里访问原型功能

时间:2015-06-03 23:10:17

标签: javascript

我正在尝试修复一些使用函数和原型函数的Javascript。出于某种原因,当我尝试访问原型函数总是未定义时,我无法弄清楚原因。

以下是我正在尝试做的一个简单示例。基本上,我想使用_open在原始Container函数声明中引用this原型。

Container();

function Container() {
    alert(this._open);
}

Container.prototype._open = function() {
    alert("hey");
}

你可以see in fiddle它只是警告“未定义”。但是this questionthis question都显示了人们这样做的例子。为什么我一直未定义?

4 个答案:

答案 0 :(得分:6)

三件事:

  • 使用new Container();代替Container();
  • 在所有new Container();次添加后移动此prototype行。
  • 调用this._open();而不是alert(this._open);来实际执行 功能。

所以你的代码应该是这样的:

function Container() {
    this._open();
}   
Container.prototype._open = function() {
    alert('open');
}
new Container();

希望这有帮助。

答案 1 :(得分:2)

function Container() {
    this._open();
}

Container.prototype._open = function() {
    alert("hey");
}

var container = new Container();

尝试以上方法。您需要使用new创建对象的实例。 否则this引用全局对象而不是原型成员。

使用没有new()的构造函数会导致奇怪的错误。由于this将引用全局对象===窗口。

答案 2 :(得分:1)

在定义后与Container()评估员联系newvar instace = new Container();

实施例

function Container() {
    this._open();
}

Container.prototype._open = function(e) {
    alert("hey");
}

var instance =  new Container();

也许你不需要两个警报。

答案 3 :(得分:1)

您的代码利用(可能是无意的)吊装。所以看起来就好像原型是在执行之前构建的,但事实上并非如此。

这就是您的代码实际上的样子

function Container(){
    alert(this._open);
}//functions are "hoisted"

Container();

Container.prototype._open = function() {
    alert("hey");
}

看看这一点,很明显,当调用Container()时,对原型的分配尚未发生 。不仅如此,Container()被称为函数,而不像实例化。像函数一样调用Container时会发生什么,this绑定不会发生。最终结果是this采用全局引用(假设脚本不处于严格模式)。此时的全局引用没有对_open属性的引用,结果undefined被警告,这就是发生的一切。

为了让它实际警告函数_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();
相关问题