skip to content
天真笔录

this指向

/ 1 min read

绑定规则

默认绑定

function foo() {
	console.log("this==========================", this);
}
foo();

这里的this指的是window,如果是严格模式下this则是undefined

隐式绑定

function foo(params) {
	console.log("this.name==========================", this.name);
}
const obj = {
	name: "tianzhen",
	foo: foo,
};
obj.foo();

这里this指的就是obj,规则:foo被谁调用,则this指向谁

显示绑定

  1. apply
function foo() {
	console.log("this==========================", this);
}
foo.apply("tianzhen");

this则是’tianzhen’ 2. call

function foo() {
	console.log("this==========================", this);
}
foo.call("tianzhen");

this则是’tianzhen’ 3. bind

function foo() {
	console.log("this==========================", this);
}
const bar = foo.bind("tianzhen");
bar();

this还是’tianzhen’

new绑定

function Person(name, age) {
	this.name = name;
	this.age = age;
}

const p1 = new Person("tianzhen", 18);

优先级

new > bind > 隐式绑定 > 默认绑定

特殊

null/undefined 默认绑定为window