本文介绍了javascript 函数绑定到什么对象(它的“this"是什么)?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我知道在函数内部是this.

var func = function {
    return this.f === arguments.callee;
    // => true, if bound to some object
    // => false, if is bound to null, because this.f === undefined
}

var f = func; // not bound to anything;

var obj = {};
obj1.f = func; // bound to obj1 if called as obj1.f(), but not bound if called as func()

var bound = f.bind(obj2) // bound to obj2 if called as obj2.f() or as bound()

您实际上不能调用 obj2.f(),因为 f 不会成为 obj2

问题是:如何在这个函数之外找到函数绑定的对象?

The question is: how to find the object, that the function is bound to, outside of this function?

我想实现这一目标:

function g(f) {
  if (typeof(f) !== 'function') throw 'error: f should be function';

  if (f.boundto() === obj)
    // this code will run if g(obj1.f) was called
    doSomething(f);

  // ....

  if (f.boundto() === obj2)
    // this code will run if g(obj2.f) or g(bound) was called
    doSomethingElse(f);
}

和不改变函数绑定对象的部分应用:

and partial application without changing the object that the function is bound to:

function partial(f) {
   return f.bind(f.boundto(), arguments.slice(1));
}

共识:

你不能这样做.要点:小心使用 bindthis :)

推荐答案

部分应用

你可以做部分应用:

Partial Application

You can do partial application:

// This lets us call the slice method as a function
// on an array-like object.
var slice = Function.prototype.call.bind(Array.prototype.slice);

function partial(f/*, ...args */) {

    if (typeof f != 'function')
        throw new TypeError('Function expected');

    var args = slice(arguments, 1);

    return function(/* ...moreArgs */) {
        return f.apply(this, args.concat(slice(arguments)));
    };

}

这个函数绑定到什么对象?

此外,对于您问题的第一部分,有一个非常直接的解决方案.不确定这是否适合您,但您可以很容易地在 JS 中修补东西.Monkey-patching bind 是完全可能的.

var _bind = Function.prototype.apply.bind(Function.prototype.bind);
Object.defineProperty(Function.prototype, 'bind', {
    value: function(obj) {
        var boundFunction = _bind(this, arguments);
        boundFunction.boundObject = obj;
        return boundFunction;
    }
});

在任何其他脚本运行之前运行它,以及任何使用 bind 的脚本,它会自动向函数添加一个 boundObject 属性:

Just run that before any other scripts get run, and any script which uses bind, it will automatically add a boundObject property to the function:

function f() { }
var o = { };
var g = f.bind(o);
g.boundObject === o; // true

(注意:我假设您在上面的 ES5 环境中,因为您使用的是 bind.)

(Note: I'm assuming you're in an ES5 environment above due to the fact that you're using bind.)

这篇关于javascript 函数绑定到什么对象(它的“this"是什么)?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-23 03:39