简体   繁体   English

使用原型从对象中的对象上调用函数

[英]Calling a function on an object from within that object with prototype

I'm running into problems when I'm trying to call a function on an object from within that same object. 尝试从同一对象内的对象上调用函数时遇到问题。 I've read that calling a function on an object from within that object is possible here , so I think it must be my use of prototype that's causing the issue. 我读过在这里可以从对象中调用对象上的函数,所以我认为这一定是由于我使用prototype引起的。 Here's an example: 这是一个例子:

function Foo() {
    this.DoStuff();
}

Foo.prototype.DoStuff = function() {
    alert("I'm frantically doing stuff!");
}

That code (or something very similar) just doesn't want to work. 该代码(或非常相似的代码)只是不想工作。 Any ideas why? 有什么想法吗?

What you have should work fine. 您所拥有的应该可以正常工作。 It's important to remember that the value of this depends on how you call the function. 重要的是要记住的价值是非常重要的this取决于你如何调用该函数。 For it to work as you expect, you need to use the new operator to call the function as a constructor: 为了使它按预期工作,您需要使用new运算符以构造函数的形式调用该函数:

var foo = new Foo(); //`this` refers to this instance of Foo

Here's a working example . 这是一个有效的例子

If you call the function like normal, this refers to the global object, which doesn't have a DoStuff property, so a TypeError is thrown. 如果像平常一样调用该函数,则this引用的是全局对象,该对象没有DoStuff属性,因此将引发TypeError。 Here's a broken example . 这是一个残破的例子

I'm going to guess that your prototype statement is declared after you try to use Foo(). 我想您尝试使用Foo()之后就声明了原型语句。

This should work: 这应该工作:

Foo.prototype.DoStuff = function() { alert("stuff") };
myfoo = new Foo();

This should NOT: 这不应该:

myfoo = new Foo();
Foo.prototype.DoStuff = function() { alert("stuff"); };

It depends on how you call Foo() . 这取决于您如何调用Foo() If you call it directly, then this refers to whatever this is in that context. 如果你直接调用它,那么this指的是什么this是在这方面。 If you call it with the new operator, then this becomes that instance of that object, and then it has access to DoStuff() . 如果用叫它new运营商,那么this会成为该对象的该实例,然后它可以访问DoStuff()

var foo = new Foo(); // works!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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