重載
函數名相同,函數的參數列表不同(包括參數個數和參數類型),根據參數的不同去執行不同的操作。在JavaScript中,同一個作用域,出現兩個名字一樣的函數,后面的會覆蓋前面的,所以 JavaScript 沒有真正意義的重載。
// 可以跟據arguments個數實現重載
function fn(){
switch(arguments.length){
case 0:
addFn(arguments.length)
break
case 1:
deleteFn(arguments.length)
}
}
function addFn(n){
console.log(`fn函數參數個數為${n+1}個`)
}
function deleteFn(n){
console.log(`fn函數參數個數為${n-1}個`)
}
fn() // fn函數參數個數為1個
fn(1) // fn函數參數個數為0個
重寫
“實例中的指針僅指向原型,而不是指向構造函數”。
“重寫原型對象切斷了現有原型與任何之前已經存在的對象實例之間的關系;它們引用的仍然是最初的原型”。
var parent = function(name,age){
this.name = name;
this.age = age;
}
parent.prototype.showProper = function(){
console.log(this.name+":"+this.age);
}
var child = function(name,age){
parent.call(this,name,age);
}
// inheritance
child.prototype = Object.create(parent.prototype);
// child.prototype = new parent();
child.prototype.constructor = child;
// rewrite function
child.prototype.showProper = function(){
console.log('I am '+this.name+":"+this.age);
}
var obj = new child('wozien','22');
obj.showProper();
上面這段代碼通過使用寄生組合繼承,實現子類私有繼承父類私有,子類公有繼承父類公有,達到重寫父類的showProper
