一、this的使用
a、无论是否在严格模式下,在全局执行环境中(在任何函数体外部)this 都指向全局对象。
示例
/ 在浏览器中, window 对象同时也是全局对象:
console.log(this === window); // true
console.log(this === globalThis)// true
console.log(this === global) //在node中
this.b = "MDN";
console.log(window.b) // "MDN"
console.log(b) // "MDN"
b、在严格模式下,如果进入执行环境时没有设置 this 的值,this 会保持为 undefined
function f2(){
"use strict"; // 这里是严格模式
return this;
}
f2() === undefined; // true
this 应是 undefined,因为 f2 是被直接调用的,而不是作为对象的属性或方法调用的
(如 window.f2())。有一些浏览器最初在支持严格模式时没有正确实现这个功能,
于是它们错误地返回了window对象。
c、在类的构造函数中,this 是一个常规对象。类中所有非静态的方法都会被添加
到 this 的原型中,静态方法不是 this 的属性,它们只是类自身的属性,
这里和Java语言有很大的不同,静态方法只能通过Example.third() 这样来访问,
不能通过实例化对象来访问,而Java是可以的
class Example {
constructor() {
const proto = Object.getPrototypeOf(this);
console.log(Object.getOwnPropertyNames(proto));
}
first(){}
second(){}
static third(){}
}
new Example(); // ['constructor', 'first', 'second']
d、不像基类的构造函数,派生类的构造函数没有初始的 this 绑定。
在构造函数中调用 super() 会生成一个 this 绑定,并相当于执行如下代码,
Base为基类,派生类不能在调用 super() 之前返回,除非其构造函数返回的是一个对象,
或者根本没有构造函数。
class Base {}
class Good extends Base {}
class AlsoGood extends Base {
constructor() {
return {a: 5};
}
}
class Bad extends Base {
constructor() {}//构造函数改为constructor(){super();} ,则就不会抛错了
}
new Good();
new AlsoGood();
new Bad(); // ReferenceError
e、对象转换
function add(c, d) {
return this.a + this.b + c + d;
}
var o = {a: 1, b: 3};
// 第一个参数是用作“this”的对象
// 其余参数用作函数的参数
add.call(o, 5, 7); // 16
// 第一个参数是用作“this”的对象
// 第二个参数是一个数组,数组中的两个成员用作函数参数
add.apply(o, [10, 20]); // 34
在非严格模式下使用 call 和 apply 时,如果用作 this 的值不是对象,
则会被尝试转换为对象。null 和 undefined 被转换为全局对象。
原始值如 7 或 'foo' 会使用相应构造函数转换为对象。
因此 7 会被转换为 new Number(7) 生成的对象,
字符串 'foo' 会转换为 new String('foo') 生成的对象
function bar() {
console.log(Object.prototype.toString.call(this));
}
bar.call(7); // [object Number]
bar.call('foo'); // [object String]
bar.call(undefined); // [object global]\
bind()方法
ECMAScript 5 引入了 Function.prototype.bind()。调用f.bind(someObject)
会创建一个与f具有相同函数体和作用域的函数,但是在这个新函数中,
this将永久地被绑定到了bind的第一个参数,无论这个函数是如何被调用的。
function f(){
return this.a;
}
var g = f.bind({a:"azerty"});
console.log(g()); // azerty
var h = g.bind({a:'yoo'}); // bind只生效一次!
console.log(h()); // azerty
var o = {a:37, f:f, g:g, h:h};
console.log(o.a, o.f(), o.g(), o.h()); // 37, 37, azerty, azerty
f、当函数作为对象里的方法被调用时,this 被设置为调用该函数的对象。
var o = {
prop: 37,
f: function() {
return this.prop;
}
};
console.log(o.f()); // 37
我们也可以先定义函数,然后再将其附属到o.f。这样做的结果是一样的:
var o = {prop: 37};
function independent() {
return this.prop;
}
o.f = independent;
console.log(o.f()); // 37
通过下面的例子,可以看出this和对象o的成员变量也没有太大的关系,最近引用才是最重要的
var o = {
prop: 37,
b:{
g:function(){return this.prop},
prop:42
}
};
console.log(o.b.g());//42
g、原型链中的this
对象 p 没有属于它自己的 f 属性,它的 f 属性继承自它的原型。
虽然最终是在 o 中找到 f 属性的,这并没有关系;查找过程首先从 p.f 的引用开始,
所以函数中的 this 指向p。也就是说,因为f是作为p的方法调用的,
所以它的this指向了p。这是 JavaScript 的原型继承中的一个有趣的特性。
var o = {
f: function() {
return this.a + this.b;
}
};
var p = Object.create(o);
p.a = 1;
p.b = 4;
console.log(p.f()); // 5
h、当函数被用作事件处理函数时,它的 this 指向触发事件的元素
// 被调用时,将关联的元素变成蓝色
function bluify(e){
console.log(this === e.currentTarget); // 总是 true
// 当 currentTarget 和 target 是同一个对象时为 true
console.log(this === e.target);
this.style.backgroundColor = '#A5D9F3';
}
// 获取文档中的所有元素的列表
var elements = document.getElementsByTagName('*');
// 将bluify作为元素的点击监听函数,当元素被点击时,就会变成蓝色
for(var i=0 ; i<elements.length ; i++){
elements[i].addEventListener('click', bluify, false);
}
i、当代码被内联 on-event 处理函数 调用时,它的this指向监听器所在的DOM元素:
<button onclick="alert(this.tagName.toLowerCase());">
Show this
</button>
但是如果this存在与多层嵌套的内层代码中,就会指向window或global对象,如下
<button onclick="alert((function(){return this})());">
Show inner this
</button>
j、和其他普通函数一样,方法中的 this 值取决于它们如何被调用。有时,
改写这个行为,让类中的 this 值总是指向这个类实例会很有用。为了做到这一点,
可在构造函数中绑定类方法:
class Car {
constructor() {
// Bind sayBye but not sayHi to show the difference
this.sayBye = this.sayBye.bind(this);
}
sayHi() {
console.log(`Hello from ${this.name}`);
}
sayBye() {
console.log(`Bye from ${this.name}`);
}
get name() {
return 'Ferrari';
}
}
class Bird {
get name() {
return 'Tweety';
}
}
const car = new Car();
const bird = new Bird();
// The value of 'this' in methods depends on their caller
car.sayHi(); // Hello from Ferrari
bird.sayHi = car.sayHi;
bird.sayHi(); // Hello from Tweety
// For bound methods, 'this' doesn't depend on the caller
bird.sayBye = car.sayBye;
bird.sayBye(); // Bye from Ferrari