1.call() apply()
var one={ name:'Amy', say:function (greet) { return greet+"!"+this.name; }};console.log(one.say("hi")); // "hi!Amy"// console.log(say());//errorvar two={ name:"Tom"};console.log(one.say.apply(two,['hello']));//"hello!Tom"2.绑定 将方法和对象绑定起来,然后返回另一个函数
var one={ name:'Amy', say:function (greet) { return greet+"!"+this.name; }};var two={ name:"Tom"};var say=one.say;console.log(say("haha"));//haha!undefinedvar another={ name:"otherObject", method:function (callback) { return callback('Bye'); }};console.log(another.method(one.say));//Bye!undefined//绑定函数function bind(obj,method) { return function () { return method.apply(obj,[].slice.call(arguments)) }}var twosay=bind(two,one.say);console.log(twosay('yoyo'));//yoyo!Tomvar other=bind(another,one.say);console.log(another.method(other));//Bye!otherObject绑定所需要的代价就是:额外闭包的开销
ECMAScript中将bind()方法添加到了Function.prototype,使得bind()就像apply()和call()一样简单易用。 var newFunc=obj.someFunc.bind(myobj,1,2,3)
PS:继承只是实现代码复用的方法之一。
新闻热点
疑难解答