0

Just out of curiosity, and to make a little experiment I have in mind, is it possible to change the type of an object after it's been created?

By changing it's type I mean to make the object respond to the instanceof operator, like this:

(as you can see, I tried changing the constructor, but it didn't work)

var MyConstructor = function() { this.name = 'no name' };
undefined

var myInstance = { name: 'some name' }
undefined

myInstance instanceof Object
true

myInstance instanceof MyConstructor
false

myInstance.constructor
function Object() { [native code] }

myInstance.constructor = MyConstructor
function () { this.name = 'no name' }

myInstance instanceof Object
true

myInstance instanceof MyConstructor
false

I guess I could create a new object with new MyConstructor(), and then delete every property from it and then copy every property from myInstance, but was wondering if there exists a simpler way...

-- UPDATE --

I do know the existence of the __proto__ property, I just discarded it upfront because I know that event though it's implemented in most browsers is not part of the standard.

opensas
  • 60,462
  • 79
  • 252
  • 386

3 Answers3

4

Since JavaScript is a prototype base language, the instanceof method is checking the object's __proto__ attribute.

So I guess your question is Can I change the prototype of the created object?

In some situations you can, but it's a bad idea.

Check the answer here: How to set the prototype of a JavaScript object that has already been instantiated?

Here is an example what I guess you're trying to do. It works on Chrome, Safari, Firefox and node.js.

Community
  • 1
  • 1
taiansu
  • 2,735
  • 2
  • 22
  • 29
1
myInstance.__proto__ = new MyConstructor()
myInstance instanceof MyConstructor
true

However this is non-standard and not a good idea according to https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/instanceof

Bemmu
  • 17,849
  • 16
  • 76
  • 93
1

In some browsers, the object's prototype is exposed via the __proto__ property, but it is unwise to use it--it can't be relied on and isn't part of the official specification.

Due to this, you should basically accept that you can't change an object's type after it is created, or mess with its prototype chain.

ErikE
  • 48,881
  • 23
  • 151
  • 196
  • 2
    I'm not sure why this was down-voted. While it is terse answer that could be expanded, it is *100% correct according to the ES5 (but maybe not ES6?) specification*. – user2246674 Jun 14 '13 at 04:50