this指针

this指针

javascript中this指针是动态的,主要是根据当前函数执行上下文及函数调用方式决定的.

  • 以函数方法调用时this指针全局或严格模式中为undefined
  • 以方法调用时this是指针当前对象实例的.
  • 以构造函数方式时this指向当前创建的实现对象
  • applycalllambda表达式 可用于绑定this指针.

注意:别绕晕了

函数方式调用

// 以函数方式调用
var x = 2
function test() {
	console.log(this.x);  // 输出 2
}
test() // this 为全局对象 windown

以方法调用

// 以方法调用
var x = "x";
let o = {
	x: 2
};
console.log(o.x);  // this指针o实例

构造函数方式

var x = 1;
function Test() {
	this.x = "5x";
}
let b = new Test();
console.log(b.x); // this指针b实例对象

apply与call绑定this

apply与call接收的函数参数不同,使用方法都是一样的.

// apply 
var b = "b"
function test() {
	console.log(this.b)
}
let o = {
	b:22
}
test.apply(o) // 打印出 22 因为把o实例对象绑定this指针上了

lambda表达式(箭头函数)

箭头函数没有this指针,箭头函数里面的this是继承上层函数this指针.在定义时就绑定了的.

// 对象字面量
var x = "x"
var o = {
	x: 1,
	test: function() {
		console.log(this.x); // this指针由调用方法决定
	}
};
var b = o.test;
b(); // 输出x, this指向全局
o.test(); // 输出1 ,this为当前对象实例

对象字面量与箭头函数

// 对象字面量与箭头函数
var x = "x";
let o = {
	x: 1,
	test: () => {
		console.log(this.x); // 这里this指针指向的是全局对象
	}
};
// 这里this指针指向新创建对象实例
let O = function() {
	this.x = 1;
	this.test = {
		x: 5,
		t: () => {
			console.log(this.x); // 输出 1, this继承于上层函数的this指针
		}
	};
};
let o = new O();
o.test.t();

实例一

以下示例中 alert 出来的结果分别是?

var color = "蓝色";
var test = {
	color: "白色",
	getColor: function() {
		var color = "red";  // 这只是一个局部变量,不是对象成员
		alert(this.color);
	}
};
var getColor = test.getColor;
getColor(); // 蓝色  this 为全局对象
test.getColor(); // 白色 this为当前对象实例

个人博客地址 : https://www.zhuamimi.cn
文章地址 : https://www.zhuamimi.cn/archives/206

原文地址:https://www.cnblogs.com/whnba/p/12335797.html