bind是第一印象中的选择。但把它放最后再看。
一,self,that
function cesi(){
let self=this
this.sj="测试数据"
this.f=function(){
console.log("测试:",self.sj);
}
this.bindcs=new bindcesi(self)
}
function bindcesi(that){
let self=this
this.sj="绑定/引用测试数据"
this.f=function(){
console.log("测试:",self.sj);
}
this.start=function(){
console.log("start");
this.f()
that.f()
}
this.start()
}
new cesi()
意义简洁明确。唯一的缺点大概就是继承写起来有点啰嗦。
二,Object.assign
Object.assign(A,A1,A2……An)用于将多个对象并入第一个对象(A)。
这里巧妙地利用了这一点。
class cesi {
constructor() {
this.sj = "cesi数据"
this.k=6
this.bindcs = new bindcesi(3,this)
this.start()
}
start() {
console.log("cesi开始")
this.f(5)
};
f(x) {
console.log("cesi:",`第${x}次测试`, 'this.sj:',this.sj,"this.k:",this.k)
}
}
class pare{
constructor(k) {
this.k=k*9
}
}
class bindcesi extends pare{
constructor(k,that) {
super(k)
this.sj = "绑定测试数据0"
this.f(1)
Object.assign(this, that)
this.f(2)
this.sj = "新绑定数据"
this.f(3)
this.start()
}
f(x) {
this.k=this.k+10
console.log(`第${x}次测试`, 'this.sj:',this.sj,"this.k:",this.k)
};
start() {
console.log("bindstart")
this.f(4);
};
}
new cesi()
通过log可以看出来,使用Object.assign(this, that)相当于把对象that并入了this。其中:
1,同名数据被顶替了。方法没顶替。
2,这边对数据的改变并不影响原对象中的数据。
三,bind
class cesi {
constructor() {
this.sj = "cesi数据"
this.k=6
this.bindcs = new bindcesi(3,this)
this.start()
}
start() {
console.log("cesi开始")
this.f(5)
};
f(x) {
console.log("cesi:",`第${x}次测试`, 'this.sj:',this.sj,"this.k:",this.k)
}
}
class pare{
constructor(k) {
this.k=k*9
}
}
class bindcesi extends pare{
constructor(k,that) {
super(k)
this.sj = "绑定测试数据0"
this.bf(1)
this.f=this.bf.bind(that)
this.f(2)
this.sj = "新绑定数据"
this.bf(3)
this.start()
}
bf(x) {
this.k=this.k+10
if(x===2){this.sj = "新绑定数据"+"x2时"}
console.log(`第${x}次测试`, 'this.sj:',this.sj,"this.k:",this.k)
};
start() {
console.log("bindstart")
this.k=7
this.sj="试试改变"
console.log(this.k,this.sj);
this.f(4)
};
}
new cesi()
1,bind使得函数f下的this,将会指向that.并且将无法方便地使用其本体的this数据,比如本体的其它函数。其对this的改变也会传递至原that,因其指向同一个数据。
2,this.bf(3)记下的log非常有启发性。
它让我意识到,this.f=this.bf.bind(that)其实是新建了一个函数,其名为f,内容与bf相同,唯一差别是其内的this指向.
3,f的this指向that(cesi的this)。bf的this指向bindsesi的this。
4,就像f没有‘顶替’bf,bf照常能用。'cesi的this'也并没有“顶替”'bindsesi的this'。
在其它没有'bind(that)'的函数,包括bf中,'bindsesi的this'照常使用与被改变。