掌握Javascript Function.bind() [英] Mastering Javascript Function.bind()

查看:62
本文介绍了掌握Javascript Function.bind()的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

function def() {
    console.log(this.x)
}

var f = def.bind({ x:777 })
f() // prints 777

bind 创建一个函数 f ,与 def 相同,但在$ $内除外c $ c> f ,设置为 {x:777}

The bind creates a function f which is identical to def, except that within f, this is set to { x:777 }.

是否可以访问对象 f 被绑定到 f ?例如, console.log(f.this.x)(但这不起作用)。或者之后的代码是否无法查看 f 绑定的对象?

Is it possible to access the object f was bound to outside of f? E.g., console.log(f.this.x) (but that doesn't work). Or is it impossible for code that comes after to see what object f was bound to?

推荐答案

我在 bind 上找到了一些有用的信息:
http://dmitrysoshnikov.com/notes/note-1-ecmascript-bound-functions/

I found some useful information on bind here: http://dmitrysoshnikov.com/notes/note-1-ecmascript-bound-functions/

bind 会产生一种轻量级函数(在某些方面与通常的函数不同,如上面的链接所述。基本上它提供了一个包装器用于调用目标函数,并维护内部属性,包括目标函数,绑定 this 和绑定参数。由于这些是内部属性,因此无法访问它们OP询问的方式(你不能采取任意绑定函数 f 并执行类似 f.getBoundThis())。

bind as specified in ECMAScript 5 produces a sort of lightweight function (which differs in some ways from usual functions, as described in the link above. Basically it provides a wrapper for calling the target function, and maintains internal properties which include the target function, the bound this, and the bound arguments. As these are internal properties, they aren't accessible in the way the OP is asking about (you can't take an arbitrary bound function f and do something like f.getBoundThis()).

值得注意的是绑定在捕获某些状态时不是唯一的。闭包也捕获状态。但是, bind (在ECMAScript 5中指定)是而不是一个闭包,因为闭包捕获变量而绑定捕获值。

It's worth noting that bind is not unique in capturing some state. Closures also capture state. However, bind (as specified in ECMAScript 5) is not a closure, because closures capture variables whereas bind captures values.

以下是一个例子:

(function () {
    var x = 2;

    function thisSquared() { return this * this; }
    f = thisSquared.bind(x);

    g = function() { return x * x; } // g is a closure

    console.log(f()); // Squares the captured value (2), prints 4
    console.log(g()); // Squares x, prints 4

    x = 3;
})();

console.log(f()); // Squares the captured value (still 2), prints 4
console.log(g()); // Squares x, prints 9

以前的一些 bind (在ECMAScript 5之前用JavaScript编写)与闭包没有区别。

Some previous implementations of bind (written in JavaScript before ECMAScript 5) didn't have this distinction from closures.

这篇关于掌握Javascript Function.bind()的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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