// Don't break the function prototype.
// pd - https://github.com/Raynos/pd
var proto = Object.create(Function.prototype, pd({
"prop": 42
}));
var f = function() { return "is a function"; };
f.__proto__ = proto;
console.log(f.hasOwnProperty("prop")); // false
console.log(f.prop); // 42
console.log(f()); // "is a function"
.__proto__
是非標準的,不推薦使用。如何繼承JavaScript功能?
我該如何繼承原型創建對象,但讓該對象成爲函數。
Object.create
返回對象不是函數。
new Constructor
返回一個對象不是函數。
動機: - 一個跨瀏覽器finherit
var finherit = function (parent, child) {
var f = function() {
parent.apply(this, arguments);
child.apply(this, arguments);
};
f.__proto__ = parent;
Object.keys(child).forEach(function _copy(key) {
f[key] = child[key];
});
return f;
};
我不相信這是可能的,所以我們也許應該提出一個Function.create
到ES-討論郵件列表
/*
Creates a new function whose prototype is proto.
The function body is the same as the function fbody.
The hash of propertydescriptors props is passed to defineproperties just like
Object.create does.
*/
Function.create = (function() {
var functionBody = function _getFunctionBody(f) {
return f.toString().replace(/.+\{/, "").replace(/\}$/, "");
};
var letters = "abcdefghijklmnopqrstuvwxyz".split("");
return function _create(proto, fbody, props) {
var parameters = letters.slice(0, fbody.length);
parameters.push(functionBody(fbody));
var f = Function.apply(this, parameters);
f.__proto__ = proto;
Object.defineProperties(f, props);
return f;
};
})();
正如在es-discuss線程中提到的,存在一個ES:稻草人<|
原型操作員將允許這一點。
讓我們來看看它會是什麼樣使用<|
var f1 = function() {
console.log("do things");
};
f1.method = function() { return 42; };
var f2 = f1 <| function() {
super();
console.log("do more things");
}
console.log(f1.isPrototypeOf(f2)); // true
console.log(f2()); // do things do more things
console.log(f2.hasOwnProperty("method")); // false
console.log(f2.method()); // 42
'console.log(f.apply);'將返回'undefined' ...因此,這種方式在任何方面都不是最佳的......仍在考慮替代方案。 –
@FelixKling我忘了我應該從'Function.prototype'繼承謝謝 – Raynos
有一個[這個問題](http://stackoverflow.com/questions/6564481/javascript-polymorphic-callable-objects)我遇到一段時間回到哪裏這個提問者引用了[這篇文章](http://ajaxian.com/archives/javascript-tips-for-rookies-and-gurus),它顯示了創建*「多態可調用對象」*的模式。不知道這是否是你之後,但可能值得一看。 – user113716