Javascript 从该数据库访问原型函数

Javascript 从该数据库访问原型函数,javascript,Javascript,我正在尝试修复一些使用函数和原型函数的Javascript。出于某种原因,当我尝试访问原型函数时,它总是未定义,我不知道为什么 这是一个简单的例子,我正在尝试做什么。基本上,我想使用this从原始容器中引用\u open原型 Container(); function Container() { alert(this._open); } Container.prototype._open = function() { alert("hey"); } 你可以说它只是提醒“未定

我正在尝试修复一些使用函数和原型函数的Javascript。出于某种原因,当我尝试访问原型函数时,它总是未定义,我不知道为什么

这是一个简单的例子,我正在尝试做什么。基本上,我想使用
this
从原始
容器中引用
\u open
原型

Container();

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

Container.prototype._open = function() {
    alert("hey");
}
你可以说它只是提醒“未定义”,但两者都显示了人们这样做的例子。为什么我一直没有定义?

在定义之后调用
Container()
,并使用
new
求值器:
var instace=new Container()

例子
函数容器(){
这个;
}
Container.prototype.\u open=function(e){
警惕(“嘿”);
}
var实例=新容器()
试试上面的方法。您需要使用
new
创建对象的实例。 否则,
引用全局对象,而不是原型成员

在没有new()的情况下使用构造函数会导致奇怪的错误。由于
将引用全局objected==窗口

三件事:

  • 使用
    新容器()而不是
    容器()
  • 移动此
    新容器()行后所有
    原型
    添加
  • 调用
    this.\u open()而不是
    警报(此打开)以实际执行
    功能
因此,您的代码应该如下所示:

function Container() {
    this._open();
}   
Container.prototype._open = function() {
    alert('open');
}
new Container();
希望这有帮助。

您的代码(可能是无意中)利用了提升。因此,看起来原型是在执行之前构建的,但事实并非如此

这就是您的代码的实际外观

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

Container();

Container.prototype._open = function() {
    alert("hey");
}
综上所述,很明显,当调用
Container()
时,对原型的赋值还没有发生。不仅如此,
Container()
的调用就像一个函数,而不是一个实例化。当像函数一样调用
容器
时会发生的情况是,
绑定不会发生。最终结果是,
采用全局引用(假设脚本未处于严格模式)。此时的全局引用没有对
\u open
属性的引用,因此
未定义
会发出警报,这就是所发生的一切

为了实际提醒函数,此处定义的_open将首先将属性
_open
分配给
容器
的原型,然后再实例化。否则,该属性将不存在于创建的对象中

接下来,实例化必须与
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();

有趣的是,你的建议让情况变得更糟。它不能解决未定义的问题。而且它也阻止了Cort3z答案中的解决方案起作用。“否则这指的是全局对象,而不是原型成员。”这真是一条很棒的信息。但有一件事我不明白<代码>此。_open
在此仍未定义。但是,如果您放置
新容器()在末尾,然后定义它。你知道为什么吗?只是想弄清楚,你可以调用
this.\u open()
无论它是在前面还是后面,但一种方式是定义它,另一种方式是未定义它。也许这值得一个完全独立的问题?this.open指的是一个不同的函数在这种情况下,这是指全局对象-window.open()。它不是原型上定义的开放函数方法。换句话说u在JSWow中没有特殊意义谢谢,这解释了为什么只有在我没有实例化
容器的新实例时才定义
.open
。。。因为
引用了全局对象。所以我的评论最初有一个打字错误,我的意思是
\u open
,而不是
open
。我的意思是问为什么你的答案中仍然没有定义
\u open
函数,尽管你可以调用该函数。在这种情况下,你必须在调用构造函数之前分配原型(就像你正在做的那样)。是的,终于有人解决了OP代码中所有错误的问题。恭喜。
//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();