有什么方法可以创建一个从另一个对象继承属性的函数/可调用对象? __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
最佳答案
这是标准格式的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();
(如果必须这样做,我也将
id
,hello
和类似的东西隐藏在闭包中,而不是使用全局变量)关于javascript - 具有继承属性的函数(可调用)对象,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/6638654/