2011-07-10 42 views
3

是否有任何方法来创建继承另一个对象的属性的函数/可调用对象?这可能与__proto__,但该属性已被弃用/非标准。有没有符合标准的方法来做到这一点?具有继承属性的函数(可调用)对象

/* A constructor for the object that will host the inheritable properties */ 
var CallablePrototype = function() {}; 
CallablePrototype.prototype = Function.prototype; 

var callablePrototype = new CallablePrototype; 

callablePrototype.hello = function() { 
    console.log("hello world"); 
}; 

/* Our callable "object" */ 
var callableObject = function() { 
    console.log("object called"); 
}; 

callableObject.__proto__ = callablePrototype; 

callableObject(); // "object called" 
callableObject.hello(); // "hello world" 
callableObject.hasOwnProperty("hello") // false 
+0

的[我如何做一个可调用JS对象具有任意可能重复原型?](http://stackoverflow.com/questions/548487/how-do-i-make-a-callable-js-object-with-an-arbitrary-prototype) – CMS

回答

1

doesn't seem to be possible以标准的方式。

你确定你不能只是使用普通复制吗?

function hello(){ 
    console.log("Hello, I am ", this.x); 
} 

id = 0; 
function make_f(){ 
    function f(){ 
      console.log("Object called"); 
    } 
    f.x = id++; 
    f.hello = hello; 
    return f; 
} 

f = make_f(17); 
f(); 
f.hello(); 

g = make_f(17); 
g(); 
g.hello(); 

(如果我不得不这样做我也想隐藏idhello和类似的东西封闭内,而不是使用全局变量)