javascript 中 this的指向情况
this指向被调用时的命名空间
1、一般情况下:this = window
2、函数中的this为函数调用时的运行环境,一般时window
3、对象的属性方法,this指向该对象
4、使用call、apply、bind时指定的的对象为this
5、()=>{} 箭头函数的this指向其所在环境的环境变量
6、new 关键字 new Constructor()
javascript中改变this指向的方法
function sum(x, y) {
return x + y + this.z;
}
1、call(this[,arg1[,arg2]])
sum.call({ z: 3 }, 1, 2); //6
2、apply(this,[…arguments])
sum.apply({ z: 3 }, [1, 2]) //6
3、bind(arg1[,arg2[,arg3]]) bind([…arguments])([…arguments])
sum.bind({z:3},1)(2); //6
4、new
function Student(age) {
this.name = 'name';
this.age = age;
this.setname = function (name) {
this.name = name;
}
this.getname = function () {
console.log(this.name);
}
}
var st=new Student(20);
st.setname('小明');
st.getname() //小明
5、箭头函数
由于箭头函数不绑定this, 它会捕获其所在(即“定义”的位置)上下文的this值, 作为自己的this值(箭头函数里面调用this是其在定义时所处环境的‘命名空间’)
() => {} item => console.log(item);
翻译
function (){} function(item){ console.log(item); }
下面是箭头函数在不同情况下的this指向:
var name = 'window.name全局';
var obj = {
name: '箭头函数',
getName: () => {
console.log(this.name);
}
}
//obj.getName() === "window.name全局"
var Student=(age)=>{
this.age = age;
this.setAge = (data) => {
this.age = data;
}
}
//Uncaught TypeError: Student is not a constructor
Array.prototype.getlength = (data) => {
console.log(this === window); //true
return this.length;
}
var array=new Array([12,13]);
//array.getlength() === undefined
this指向引申问题
不能使用箭头函数的情况
1、对象的属性方法:无法获得当前对象的属性值
2、构造函数:this指向其定义上下文,new的过程中依然无法指向新生成的对象
3、原型链上添加方法:this始终指向其定义上下文,无法获取新生成对象原型链上的属性
js源码实现bind功能
Function.prototype.bind = function (content) {
var self = this,
args = Array.from(arguments);
return function () {
var innerArgs = Array.from(arguments);
var finalArgs = args.concat(innerArgs);
return self.apply(content, finalArgs);
}
}
function sum(x, y, z) {
return x + y + z;
}
var a = sum.bind(1, 2, 3)();
var b = sum.bind(1)(2, 3);
a;b;