2011-07-10 43 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和類似的東西封閉內,而不是使用全局變量)