// 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__
non standard e obsoleto.Come ereditare le funzioni javascript?
Come dovrei ereditare la creazione prototipica di un oggetto ma avere quell'oggetto essere una funzione.
Object.create
restituisce un oggetto non una funzione.
new Constructor
restituisce un oggetto non una funzione.
Motivazione: - Un cross-browser 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;
};
io non credo che questo è possibile, in modo probabilmente dovremmo proporre una Function.create
ai es-discuss mailing list
/*
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;
};
})();
Come indicato nel thread es-discuss esiste a ES: strawman <|
operatore prototipo che consentirebbe questo.
Vediamo cosa sarebbe simile utilizzando <|
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);' restituirà 'undefined' ... in modo che il modo non sia ottimale in alcun modo ... continuando a pensare ad un'alternativa. –
@FelixKling Ho dimenticato che dovrei ereditare da 'Function.prototype' grazie – Raynos
C'era [questa domanda] (http://stackoverflow.com/questions/6564481/javascript-polymorphic-callable-objects) Ho incontrato un po 'di tempo fa il richiedente indicato [questo articolo] (http://ajaxian.com/archives/javascript-tips-for-rookies-and-gurus) che mostrava un modello per la creazione di * "oggetti calorici polimorfi" *. Non sono sicuro se è quello che stai cercando, ma potrebbe valere la pena dare un'occhiata. – user113716