this 是什么
this是一个迥殊的关键字 this能够用在组织函数当中,示意实例对象 this老是返回一个对象
简单说,this就是属性或要领“当前”地点的对象
var person = {
name: 'Rookie',
method: function () {
return '姓名:'+ this.name;
}
};
person.method() //"姓名:Rookie"
this.name示意name属性地点的谁人对象。由于this.name是在method要领中挪用,而method要领地点的当前对象是person,因而this指向person,this.name就是person.name。
由于对象的属性能够赋给另一个对象,所以属性地点的当前对象是可变的 —-> this的指向是可变的
var A = {
name: 'Rookie',
method: function () {
return '姓名:'+ this.name;
}
};
var B = {
name: 'BDD'
};
B.method= A.method;
B.method() // "姓名:BDD"
运用场景
(1)全局环境
全局环境运用this,它指的就是顶层对象window
this === window // true
function f() {
console.log(this === window);
}
f() // true
不论是否是在函数内部,只假如在全局环境下运转,this就是指顶层对象window
(2)组织函数
组织函数中的this,指的是实例对象。
var Obj = function (e) {
this.e = e;
};
var n=new Obj('HOLA');
console.log(n.e);
this指向实例对象,所以在组织函数内部定义this.e,就相当于定义实例对象有一个e属性。
(3)对象的要领
假如对象的要领内里包括this,this的指向就是要领运转时地点的对象。该要领赋值给另一个对象,就会转变this的指向。
var obj ={
foo: function () {
console.log(this);
}
};
obj.foo() // obj
obj.foo要领执行时,它内部的this指向obj
var a = {
p: 'Hello',
b: {
m: function() {
console.log(this.p);
}
}
};
a.b.m() // undefined
假如this地点的要领不在对象的第一层,这时候this只是指向当前一层的对象,而不会继续更上面的层。