js bind 理解笔记
原文链接: https://blog.youkuaiyun.com/qq_39148344/article/details/90173640看的他的 我只是加强一下印象
function.prototype.bind():
bind():方法主要就是将函数绑定到某个对象上 ,
例如:f.bind(obj),实际上可以理解为 obj.f(),这时f函数体内的this指向obj;
var a = {
b: function() {
var func = function() {
console.log(this.c);//this指向window 没有c这个属性所以输出 undefined
}
func();
},
c: 'hello'
}
a.b();
console.log(a.c);
那么问题来了当我们希望func()他的输出的值就是为hello怎么办
方法一 改变this的值
var a = {
b: function() {
var _that=this//通过赋值的方式将this赋值给that
var func = function() {
console.log(_that.c)
}
func();
},
c: 'hello'
}
a.b(); //hello
console.log(a.c); //hello
方法二:绑定this的值发生改变
//使用bind方法1
var a = {
b: function() {
var func = function() {
console.log(this.c)
}.bind(this)
func();
},
c: 'hello'
}
a.b(); //hello
console.log(a.c); //hello
//使用bind方法2
var a = {
b: function() {
var func = function() {
console.log(this.c)
}
func.bind(this)();
},
c: 'hello'
}
a.b(); //hello
console.log(a.c); //hello
这里我们以a.b()的形式去执行a对象中的b这个函数,是经过对象a的所以当我们来执行a对象中b函数的时候找this就会先找到a对象所以在a对象中的b这个函数中的this为a对象,所以这个时候bind,绑定的this也就是为a对象了
c='haha'
var a = {
b: function () {
console.log(this);//window
var func = function () {
console.log(this.c);//haha
}.bind(this);
func();
},
c: 'hello'
}
var d=a.b;
d()
这里我们以d()的形式去执行a对象中的b这个函数吗,因为d()的执行的时候由于没人应用this默认为window,所以在a对象中的b这个函数中的this为window,所以不这个时候bind,绑定的this也就是为window了
JS Bind 方法详解
2879

被折叠的 条评论
为什么被折叠?



