Kann ich ein JavaScript-Objekt ohne das neue Schlüsselwort erstellen?
Folgendes möchte ich tun:
function a() {
// ...
}
function b() {
// Some magic, return a new object.
}
var c = b();
c instanceof b // -> true
c instanceof a // -> true
b instanceof a // -> true
Ist es möglich? Ich kann machenb
sei eine Instanz vona
leicht durch Einhakena
in seine prototypenkette muss ich dann aber machennew b()
Das versuche ich zu vermeiden. Ist das was ich will möglich
Aktualisieren: Ich denke, dass es mit vernünftigem Gebrauch von möglich sein könnteb.__proto__ = a.prototype
. Ich werde nach der Arbeit noch mehr experimentieren.
Update 2: Unten ist das, was am nächsten zu sein scheint, was gut genug für mich ist. Vielen Dank für die interessanten Antworten.
function a() {
// ...
}
function b() {
if (!(this instanceof arguments.callee)) {
return new arguments.callee();
}
}
b.__proto__ = a.prototype
var c = b();
c instanceof b // -> true
c instanceof a // -> false
b instanceof a // -> true
Update 3: Ich habe genau das gefunden, was ich wollteBlogbeitrag über 'Kraftbauer', sobald ich das Wesentliche hinzugefügt habeb.__proto__ = a.prototype
Linie:
var object = (function() {
function F() {}
return function(o) {
F.prototype = o;
return new F();
};
})();
function a(proto) {
var p = object(proto || a.prototype);
return p;
}
function b(proto) {
var g = object(a(proto || b.prototype));
return g;
}
b.prototype = object(a.prototype);
b.__proto__ = a.prototype;
var c = b();
c instanceof b // -> true
c instanceof a // -> true
b instanceof a // -> true
a() instanceof a // -> true