Suppose I have 2 constructors and a member function defined
function A() {}
function B() {}
A.prototype.a = function(){}
And I’ve instantiated a B. How can I force a conversion to make it an A?
o = new B();
//What should I put here?
o.a();
I’m new to js. And I have a feeling that whether o mentioned above is an A or a B is merely controlled by a reference to a prototype. Therefore, I feel typecast should be possible.
Answers, as well as explanations that can help me understand js objects, are welcomed.
You can’t change (that is, completely swap-out) the prototype of an object once it’s been created (yet; in a future version of JavaScript, it’s likely to be possible).
Objects in JavaScript are enormously malleable, though. You can do this, for instance:
…and then
owill have theafunction. If you wanted to give it all of the enumerable properties ofA.prototype(including any from its prototype):The
prototypeproperty of functions is a completely normal, boring object assigned to a normal, boring property on the function. When you usenewto create an object using that function (which is called a “constructor function”), the function’sprototypeproperty is assigned to the newly-created object as its underlying prototype (which has no name you can access in code [yet]).As of ES5 (reasonably supported in Chrome, Firefox, Opera, and IE9; not in IE8 and earlier), you can get the prototype of an object via
Object.getPrototypeOf, and you can create objects assigning them a prototype without going through constructor functions by usingObject.create, but you can’t change what an object’s prototype is once it’s been created.Some JavaScript engines (like the one in Firefox) have a currently-non-standard extension called
__proto__which lets you directly access and manipulate the prototype of an object, by treating it as a property. E.g.:…but that is not standard at present. It may well be part of the next standard, though. If you’re interested in information about the upcoming ES6, you can find draft specifications and such here.