4

我正在阅读这篇文章http://dev.opera.com/articles/view/objects-in-javascript/ 在那里我读到“'this'关键字并不总是指定义方法的对象,但是而是可以根据具体情况而改变。” 我找不到任何示例,其中“this”不引用定义方法上的对象....如果可能,请给我一个示例

4

6 回答 6

3

一个你可能会遇到但没想到会出现这种结果的例子:

var obj = {
    testFunc : function(){
        alert("testFunc: " + this);
    }
}

obj.testFunc();  // this is the object

setTimeout(obj.testFunc, 1000);  // this is window

http://jsfiddle.net/t7ycd/

于 2012-10-10T21:15:49.437 回答
2

有很多方法可以改变上下文。jsfiddle

使用绑定:(旧 IE 浏览器不支持(IE < 9))

    var obj = {}; 
    function fun1(){};
    obj2 = {};
    obj2.fun1 =  fun1.bind(obj);
    obj2.fun1(); // context inside fun1 would be obj.

使用应用或调用。

var obj = {}; 
        function fun1(){};
        obj2 = {};
        obj2.fun1 =  function(){
            fun1.apply(obj, arguments);
            //or fun1.call(obj, ar1, arg2,...);
          };
        obj2.fun1(); // context inside fun1 would be obj. 
于 2012-10-10T21:12:19.523 回答
1

这是一种方法

var a = {};
a.foo = function(){ console.log(this); }
a.foo(); // object a
a.foo.call(window); // window object
于 2012-10-10T21:13:19.530 回答
0

如果您从 A 类调用 B 类中的方法,“this”将引用调用该方法的类 - A,而不是它所在的类。

于 2012-10-10T21:12:06.447 回答
0

这是直接取自 Mozilla 文档的示例

https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Operators/this

var o = {prop: 37};

function independent() {
  return this.prop;
}

o.f = independent;

console.log(o.f()); // logs 37

所以这个函数independent是在全局上下文中定义的,然后附加到一个对象上。当在该对象上调用它时,上下文成为调用函数的对象,而不是定义函数的对象。

call您可以使用 javascript和bind方法以及使用匿名函数来获得类似的结果。

于 2012-10-10T21:13:10.193 回答
0

像这样

var MyObject = function()
{
 this.initialize();
}

MyObject.prototype.SomeMethod = function()
{
 //common fix is to use
 //var self = this;
 (function(){
    //this has lost scope
    //self will retain the this scope that was desired
 })();
}   
于 2012-10-10T21:13:56.503 回答