说明:本文中有借鉴其他大牛的文章,旨在共同学习,不做也不得作商用!
bind()方法主要就是将函数绑定到某个对象上,改变函数this的指向。
bind()会创建一个函数。
函数体内的this对象的值会被绑定到传入bind()中的第一个参数的值,例如:f.bind(obj),实际上可以理解为obj.f(),这时f函数体内的this自然指向的是obj;
var a = {
b: function() {
console.log(this); //a对象;因为 a.b() 这个函数的执行环境上下文是 a 对象
var func = function() {
console.log(this) //window 对象; 因为 func() 函数执行的上下文环境是 window 对象
console.log(this.c); //undefined; 因为 window.c 是undefined
}
func();
},
c: ‘hello‘
}
a.b();
console.log(a.c); //hello
改变 this 的指向问题
方式一:改变 this 的值
var a = {
b: function() {
var _this = this;
console.log(_this); //a对象;因为 a.b() 这个函数的执行环境上下文是 a 对象
var func = function() {
console.log(_this) //a对象;
console.log(_this.c); //hello
}
func();
},
c: ‘hello‘
}
a.b();
console.log(a.c); //hello
方式二:绑定this的值发生改变
// 使用bind方法一
var a = {
b: function() {
var func = function() {
console.log(this.c);
}.bind(this); //这里bind(this)的时候,这里的this指的是a对象的上下文环境,所以这时func的this对象就绑定到a上了
func();
},
c: ‘hello‘
}
a.b(); // hello
console.log(a.c); // hello
// 使用bind方法二
var a = {
b: function() {
var func = function() {
console.log(this.c);
}
func.bind(this)();
},
c: ‘hello‘
}
a.b(); // hello
console.log(a.c); // hello
//注意一下两点:
var a = {
b: function() {
var func = function() {
console.log(this.c);
};
func.bind(this);//函数是一个对象,它有 bind() 等一些属性方法。 不能写成 func().bind(this);
},
c: ‘hello‘
}
a.b(); // 这里不打印内容,因为bind()只是返回了一个函数,而 func.bind(this) 只是相当于得到了一个返回的函数,并没有执行。需要 改写成 func.bind(this)()
console.log(a.c); // hello
方法的重用,可以编写能够在不同对象上使用的方法。
通过 call()
,您能够使用属于另一个对象的方法。
语法:obj1.(method).call(obj2,argument1,argument2)
就是 obj2 可以使用 obj1 中的方法
var person = {
fullName: function() {
return this.firstName + " " + this.lastName;
}
}
var person1 = {
firstName:"Bill",
lastName: "Gates",
}
var person2 = {
firstName:"Steve",
lastName: "Jobs",
}
person.fullName.call(person1); //person1调用person的的fullName 方法。 将返回 "Bill Gates"
call()
方法可以传参,但是其参数只能从第二个开始,单个传入:
var person = {
fullName: function(city, country) {
return this.firstName + " " + this.lastName + "," + city + "," + country;
}
}
var person1 = {
firstName:"Bill",
lastName: "Gates"
}
person.fullName.call(person1, "Seattle", "USA");
原文:https://www.cnblogs.com/ymwmn/p/14636661.html