【发布时间】:2011-10-31 06:31:17
【问题描述】:
我在 javascript 中使用“this”时遇到了一个令人困惑的问题。我有一个方法'get_data',它返回一个对象的一些成员变量。有时它会返回给我对象本身......我不知道为什么。有人可以解释这里发生了什么吗?
function Feed_Item(data) {
this.data = data;
this.get_data = function() {
return this.data;
}
this.foo = function() {
return this.foo2();
}
this.foo2 = function() {
//here type of this.data() == Feed_Item!!! It should be of type Data
}
this.bar = function() {
//here type of this.data() == Data, as I'd expect
}
}
【问题讨论】:
-
您必须向我们展示调用方法的代码 - 因为
this依赖于调用,它可能会产生影响。另外,this.data()是什么?除了data参数之外,您没有名为data的函数。data是函数吗? -
函数的 this 关键字的值完全取决于它的调用方式。阅读'this' keyword, not clear的答案。
-
你真的需要
this.get_data()吗?你不能打电话给this.data吗?这似乎是你在 Java/C++ 中会做的事情,其中一些属性是私有的。
标签: javascript