今天在學習JS的原型時,遇到了一個很郁悶的問題,請看代碼:function Fn(a, b) { this.a = a this.b = b}/* 直接給函數(shù)對象添加屬性 */Fn.x = 'test'Fn.hello = function () { console.log('hello')}/* 給構造函數(shù)添加屬性 */Fn.prototype.constructor.what = 'what?'Fn.prototype.constructor.wtf = function () { console.log('wtf')}/* 給函數(shù)對象的原型對象添加屬性 */Fn.prototype.say = function () { console.log('say')}var f = new Fn('is a', function () { console.log('is b')})console.log(Fn.x); //testconsole.log(Fn.hello()); //helloconsole.log(Fn.a)console.log(f.a)console.log(Fn.what)console.log(Fn.wtf())console.log(Fn.b)console.log(f.b())console.log(Fn.say)console.log(f.say())輸出的結果令人費解:有些 undefined 是怎么出來的呢?
一個很令人困惑的JS原型的問題?
三國紛爭
2018-12-19 18:19:04