2017-02-15 93 views
1

我正在編寫一些JavaScript類(舊學校,不使用ES2015/ES6,我不想使用Babel或其他轉換器),並且我有一個繼承另一個,覆蓋其中一個父方法。對原型類使用對象文字

所以,我有我的初步App.Hello類:

var App = {}; 
App.Hello = function(args) { 
    this.name = args.name; 
} 
App.Hello.prototype = { 
    constructor: App.Hello, 
    sayHello: function() { 
     console.log('Hello, ' + this.name); 
    }, 
    sayGoodbye: function() { 
     console.log('Goodbye, ', this.name); 
    } 
} 

的然後我App.Yo類從它繼承:

// inherits from App.Hello 
App.Yo = function(args) { 
    App.Hello.call(this, args); 
} 
App.Yo.prototype = Object.create(App.Hello.prototype); 
App.Yo.prototype = { // want to combine this with above! 
    constructor: App.Yo, 
    sayHello: function() { 
     console.log('Yo, ', this.name); 
    } 
} 

但是因爲我使用對象字面結構我改寫的原型App.Yo當我通過它constructorsayHello方法後設置Object.create。所以我沒有從App.Hello繼承sayGoodby方法

1.我怎樣才能解決這個問題,但使用文字結構?

我知道我可能只是這樣做:

App.Yo.prototype = Object.create(App.Hello.prototype); 
App.Yo.prototype.constructor = App.Yo; 
App.Yo.prototype.sayHello = function sayHello() { 
    console.log('Yo, ', this.name); 
} 

但我想保持字面結構,我的課將會有很多在他們不同的方法。所以想保持它的漂亮和整潔。

2.是否可以將整個類嵌套爲文字?那麼構造函數也嵌套爲文字的一部分嗎?

例如

App.Hello = function(args) { 
    this.name = args.name; 
} 

App.Yo = function(args) { 
    App.Hello.call(this, args); 
} 

回答

1
  1. 我怎樣才能解決這個問題,但使用文字結構?

使用Object.assign,這是在ES2015添加,但它可以polyfilled所以你不必transpile:

App.Yo.prototype = Object.assign(Object.create(App.Hello.prototype), { 
    constructor: App.Yo, 
    sayHello: function() { 
     console.log('Yo, ', this.name); 
    } 
}); 

或者,如果你不想填充工具,只需用自己的助手,像標準extend功能(jQuery有一個叫$.extend,像許多其他工具庫):

function extend(target) { 
    var i, source; 
    for (i = 1; i < arguments.length; ++i) { 
     source = arguments[i]; 
     Object.keys(source).forEach(function(name) { 
      target[name] = source[name]; 
     }); 
    } 
    return target; 
} 

App.Yo.prototype = extend(Object.create(App.Hello.prototype), { 
    constructor: App.Yo, 
    sayHello: function() { 
     console.log('Yo, ', this.name); 
    } 
}); 
  1. 是否可以將整個類嵌套爲文字?

是的,通過進一步輔助功能。例如:

function derive(base, props) { 
    var cls = function() { 
     return base.apply(this, arguments); 
    }; 
    cls.prototype = Object.create(base.prototype); 
    Object.assign(cls.prototype, props); // Or use your `extend` here 
    return cls; 
} 

App.Yo = derive(App.Hello, { 
    constructor: App.Yo, 
    sayHello: function() { 
     console.log('Yo, ', this.name); 
    } 
}); 

當然,也有很多你在Yo與使用該參數的功能從缺,就像控制傳遞到Hello

如果你想進一步探索,你可以看看我的Lineage library,這使得在ES5中創建類,並且以前是相當簡單和聲明性的。就我個人而言,我認爲它已經過時了,因爲ES2015和transpiling,但你已經說過你不想使用一個transpiler ...