-
-
Save kangax/343907 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* MODIFY PROTOTYPE */ | |
var _fn=function(){}; | |
_fn.prototype.a=1; | |
var v=new _fn(); | |
alert(v.a === 1); /* true */ | |
alert(v.constructor === _fn); /* true */ | |
/* REPLACE PROTOTYPE */ | |
var _fn=function(){}; | |
_fn.prototype={a:1}; | |
var v=new _fn(); | |
alert(v.a === 1); /* true */ | |
alert(v.constructor === _fn); /* false in ie; true in other browsers */ | |
/* | |
This should be `false` in other browsers as well. | |
This is because `constructor` property is resolved on `Object.prototype` | |
(during `v.constructor` property lookup, constructor is not found on object directly, | |
so it's searched in next object in prototype chain, which is `_fn.prototype`; | |
it's not found there either, and so search goes on further to `Object.prototype`, | |
where `constructor` is finally found; it refers to `Object` there (unless overwritten), | |
which is what you're seeing in next line). | |
*/ | |
/* but */ | |
alert(v.constructor === Object.prototype); /* true in ie. ie set 'constructor' property eq Object if 'prototype' replaced | |
^--- It doesn't really set anything. | |
`constructor` is found through prototype chain during property lookup. | |
REPLACE PROTOTYPE WITH FIXING BUG OF IE */ | |
var _fn=function(){}; | |
_fn.prototype={a:1}; | |
/* | |
^--- or you can just add "constructor" here, and reference proper object in it. | |
e.g.: _fn.prototype = { a: 1, constructor: _fn }; | |
*/ | |
var v=new _fn(); | |
v.constructor=_fn; /* set 'constructor' property by hands */ | |
alert(v.a === 1); /* true */ | |
alert(v.constructor === _fn); /* now true in all browsers */ |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment