我的“这个"在哪里?使用对象方法作为回调函数 [英] Where is my 'this'? Using objects method as a callback function

查看:18
本文介绍了我的“这个"在哪里?使用对象方法作为回调函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个关于 javascript 规范或函数指针(委托?)的实现的一般问题,这些指针指向对象方法.

I have a generic question about javascript specification or implementation of functions pointer (delegates?) which are points to object methods.

请阅读以下代码片段.这里我们有一个带有方法的对象,使用this"来访问对象字段.当我们像往常一样调用这个方法(o.method();)时,返回对象的指定字段的值.但是当我们创建指向这个方法的指针(回调)并调用它时,返回一个未定义的值,因为方法范围内的this"现在是全局对象.

Please, read the following code snippet. Here we have an object with a method using 'this' to access an object field. When we call this method as usual (o.method();), returns value of the specified field of the object. But when we create pointer to this method (callback) and invoke it, returns an undefined value, because 'this' inside method's scope now is global object.

var o = {
    field : 'value', 
    method : function() {
        return this.field;
    }
};

o.method(); // returns 'value'

var callback = o.method;

callback(); // returns 'undefined' cause 'this' is global object

那么,我的这个"在哪里?

So, where is my 'this'?

推荐答案

this"是后期绑定.也就是说,它会在函数执行之前绑定到一个事物上.它绑定到什么取决于你如何调用你的函数.

"this" is late binding. that is, it gets bound to a thing just before the function is executed. What it is bound to depends on how you call your function.

如果你这样称呼它(函数调用):

if you call it like (function invokation):

   myfunction();

this"绑定到全局对象

"this" is bound to the global object

如果你称之为(方法调用):

if you call it like (method invokation):

   myobject.myfunction();

this"绑定到myobject"

"this" gets bound to "myobject"

你也可以这样调用(调用调用):

you can also call it like so (call invokation):

   myfunction.call(myobject);

在这种情况下,this"会绑定到 myobject

in which case "this" gets bound to myobject

还有(构造函数调用):

there is also (constructor invokation):

 new MyFunction();

其中this"绑定到一个新构造的空白对象,其原型为 MyFunction.prototype.

in which "this" gets bound to a newly constructed blank object whose prototype is MyFunction.prototype.

无论如何,这就是 javascript 的创建者谈论它的方式.(我认为在规范中是这样讨论的)调用函数的不同方式.

this is how the creators of javascript talk about it, anyway. (and I think it is discussed this way in the spec) Different ways of invoking a function.

ecmascript 标准的新版本 (ecmascript5) 包括原型库的bind"方法,该方法返回一个新函数,其中this"预先绑定到您指定的内容.例如:

the new version of the ecmascript standard (ecmascript5) includes the prototype library's "bind" method, which returns a new function with "this" prebound to something you specify. for instance:

  mynewfunction = myfunction.bind(myobject);
  mynewfunction();

mynewfunction 的调用已经将this"绑定到了 myobject.

the invokation of mynewfunction has "this" already bound to myobject.

这篇关于我的“这个"在哪里?使用对象方法作为回调函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆