1

The following code alerts 'undefined.' Can I make it alert '2' without changing the first three lines?

var b = function(){}
b.prototype.c = 2
var a = {}

a.constructor = b
alert(a.c)

fiddle: http://jsfiddle.net/FHLgR/4/

Lyn Headley
  • 11,368
  • 3
  • 33
  • 35
  • The internal `[[Prototype]]` is established as an inaccessible property when an object is constructed. The public constructor property is just a convenience that can be set to any value (as you've discovered) and has no effect on the value of `[[Prototype]]`. However, a `__prototype__` property may be introduced in a future version of ECMAScript (see basilikum's answer). – RobG Jul 24 '13 at 23:11

1 Answers1

3

You can, but I think it's non-standard and therefore not supported by every browser:

a.__proto__ = b.prototype;
basilikum
  • 10,378
  • 5
  • 45
  • 58
  • 2
    I really don't recommend doing this unless you have too. That being said you shouldn't have to. Its not supported by all browsers => http://stackoverflow.com/a/3082878/243568. The docs for __proto__ can be seen here => https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/proto. – Robert Hurst Jul 24 '13 at 23:05
  • 1
    @RobertHurst I'm not saying it's a good idea but it's as far as I know the only way to achieve what he is trying to do. But of course your right. – basilikum Jul 24 '13 at 23:08
  • I agree with your answer. I'm not critical of it, actually I was about to post the same answer. I just wanted point out how bad an idea this is. – Robert Hurst Jul 24 '13 at 23:14
  • @RobertHurst absolutely no offense taken. And thanks for pointing it out and for the extra infos in your comment. – basilikum Jul 24 '13 at 23:30