var obj = {};
function addMethod(object, name, fn) {
var old = object[name];
object[name] = function() {
if(fn.length == arguments.length) {
return fn.apply(this, arguments);
}else if(typeof old == 'function'){
return old.apply(this,arguments)
}
};
}
addMethod(obj, 'sex', function() {console.log(1)});
addMethod(obj, 'sex', function(a) {console.log(a)})
应用:
var obj = {
values: ['a', 'b', 'c', 'd']
};
function addMethod(object, name, fn) {
var old = object[name];
object[name] = function() {
if(fn.length == arguments.length) {
return fn.apply(this, arguments);
}else if(typeof old == 'function'){
return old.apply(this,arguments)
}
};
}
addMethod(obj, 'find', function() {
console.log(this)
return this.values
});
addMethod(obj, 'find', function(name) {
var ret = [];
for(var i = 0, len = this.values.length; i < len; i++) {
if(this.values[i].indexOf(name) == 0) {
ret.push(this.values[i]);
}
}
return ret
});
bind函数实现
Function.prototype.bind = function() {
var fn = this,
args = Array.prototype.slice.call(arguments);
object = args.shift();
return function() {
console.log(object, args.concat(Array.prototype.slice.call(arguments)))
return fn.apply(object, args.concat(Array.prototype.slice.call(arguments)))
}
}