在使用constructor function來創造物件時,如下:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 |
function Hero (name) { this.name = name; this.occupation = 'Ninja'; this.whoAreYou = function() { return 'I\'m ' + this.name + '&I\'m ' + this.occupation; }; } var h1 = new Hero('Tombear'); var h2 = new Hero('cokey'); console.log(h1.whoAreYou()); /* I'm Tombear&I'm Ninja */ console.log(h2.whoAreYou()); /* I'm cokey&I'm Ninja */ var h = Hero('Kelly'); console.log(h.whoAreYou()); /* output undefined */ var h3 = new h2.constructor('James'); /* h2.constructor == Hero */ console.log(h3.whoAreYou()); /* I'm Ken&I'm Ninja */ |
如果你call一個被設計成constructor的function,就必須被限定使用new來創造全新的物件,如果沒有用,他可能會運作得不如你的想像,因為這個function沒有return任何東西,所以會是undefined出現,沒有用new範例裡的this會直接指到global object!