如何确定函数是一种方法的对象?

时间:2008-11-22 18:19:55

标签: javascript

var A = {
    x : function () { }
};

var b = function (method) {
    //want to know method's "parent" here
};

b(A.x);

我想知道当我调用b(A.x)时,x在A中定义。这可能吗?

4 个答案:

答案 0 :(得分:4)

没有很好的内置方法可以做到这一点,因为实际上Javascript中没有方法。它们是恰好恰好在某处分配的独立Function对象。

如果你每次创建新的函数实例(例如闭包) [感谢Matthew Crumley指出那个] ,那么你可以修改函数对象以明确地将它与它的父对象关联:

x.parent = A;

然后你可以正确地调用它,就好像它是一个方法:

x.call(x.parent);

否则你必须传递函数及其父对象。

答案 1 :(得分:2)

这个问题从语言的角度来看没什么意义,因为许多对象上可能存在一个函数。

var a = { name : 'a' },
    b = { name : 'b' },
    c = { name : 'c' }; 
a.x = function () { alert( this.name ); };
c.x = b.x = a.x;  // a, b, and c all reference the same function

您可以使用您想要的任何上下文调用x函数:

a.x(); // alerts "a" because "this" is object a 
b.x(); // alerts "b" because "this" is object b 
a.x.call( b ); // alerts "b" because "this" is object b (via parameter)

您可以操纵此行为以适合您:

var b = function ( method ) {
  // parent = this;
};
b.call( A, A.x );

然而,没有任何方法可以从函数内部知道它被分配给哪个对象,因为这不一定是一个地方。

答案 2 :(得分:2)

即使添加父属性也不会在所有情况下都有效,因为如果函数在对象的原型中,则只有一个函数对象的副本,因此无法分辨它来自哪个实例。以下是显示问题的示例:

function MyClass() {
    // Create a MyClass object
}
MyClass.prototype.x = function() { return 42; };

var a = new MyClass();
a.x.parent = a; // Set the parent to a

var b = new MyClass();
b.x.parent = b; // b.x and a.x both reference the same function from MyClass.prototype

现在,a.x.parentb.x.parent都设置为b。

只要每个对象都有自己的函数副本,

@ porneL的方法就会起作用。

最好修改函数以获取父对象和方法,以便它可以与任何函数一起使用。

答案 3 :(得分:0)

Every function in JavaScript is actually a Function object.

<html>
<body>
<script>
var A = {
    x: function (a_a, a_b) { alert(a_a + a_b);  }
};

var b = function (a_method) {
    alert(a_method.toString());
    a_method.call(this, 1, 2);
};

b(A.x);
</script>
相关问题