多应用+插件架构,代码干净,二开方便,首家独创一键云编译技术,文档视频完善,免费商用码云13.8K 广告
[TOC] Javascript的函数也是[对象](),它有三种方法可以改变函数内部this关键字的指向。 ## 1.bind ~~~ var name = "li"; var cheng = { name:"cheng" } var test = function(){ console.log(this.name) }.bind(cheng); test(); ~~~ ~~~ function sayName(){ console.log(this.name); } var person = { name:"cheng" } sayName.bind(person)(); ~~~ ## 2.call ~~~ call(thisObj,params) //第一个参数指向函数内部的this,之后的参数是需要被传入函数的参数 ~~~ ~~~ function sayName(label) { console.log(label + ":" + this.name); } var name = "window"; var cheng = { name: "cheng" }; var jiang = { name: "jiang" }; sayName.call(this,"window"); sayName.call(cheng,"cheng"); sayName.call(cheng,"cheng"); ~~~ 功能 1.改变函数内部this关键字的指向 2.可以让对象拥有一个它没有的方法 ~~~ var cheng = { name:"cheng", say(){ console.log("喜欢吃面") } } var jiang ={}; cheng.say.call(jiang); ~~~ ## 3.apply() ~~~ apply(thisObj,[params]) ~~~ ~~~ var person = { name : 'cheng', sayName(label){ console.log(label+":"+this.name); } } var jiang = { name:"jiang" } person.sayName.call(jiang,["jiang"]) ~~~