jsの関数を再ロードします.
2282 ワード
function overLoading () {
switch(arguments.length) {
case 0:
//
break;
case 1:
//
break;
case 2:
// ...
}
}
// people find ,
// , people.values ,
// , firstName value
// , firstName lastName value
var people = {
values: ["Dean Edwards", "Alex Russell", "Dean Tom"]
}
addMethod(people, 'find', function () {})
addMethod(people, 'find', function(a) {})
addMethod(people, 'find', function(a, b) {})
function addMethod (object, name, fn) {
let old = object[name]
object[name] = function () {
if(arguments.length === fn.length) {
return fn.apply(this, arguments)
} else if(typeof old === 'function') {
return old.apply(this, arguments)
}
}
}
// addMethod people.find
addMethod(people, 'find', function(){
return this.values
})
addMethod(people, 'find', function(firstName) {
let ret = []
for(var i =0 ;i < this.values.length; i++) {
if(this.values[i].indexOf(firstName) === 0) {
ret.push(this.values[i])
}
}
return ret;
})
addMethod(people, 'find', function(firstName, lastName) {
let ret = []
for(var i =0 ;i < this.values.length; i++) {
if(this.values[i] === firstName + ' ' + lastName) {
ret.push(this.values[i])
}
}
return ret
})
console.log(people.find()) //["Dean Edwards", "Alex Russell", "Dean Tom"]
console.log(people.find('Dean')) // ["Dean Edwards", "Dean Tom"]
console.log(people.find('Dean', 'Edwards')) //["Dean Edwards"]