关于this

全局的this(浏览器)
console.log(this.document===document); //true
console.log(this===window); //true
this.a=37;
console.log(window.a); //37


一般函数的this(浏览器)
function f1(){
return this;
};
f1()===window; //true

function f2(){
"use strict";
return this;
};
f2()===undefined; //true


作为对象方法的函数的this
例1:
var o={
prop:37,
f:function(){
return this.prop;
}
};
console.log(o.f()); //37 当我们给对象的属性创建方法是,我们称这个方法为对象方法

例2:
var o={prop:37};
function independent(){
return this.prop;
};
o.t=independent;
console.log(o.t()); //37



对象原型链上的this
var o={f:function(){
return this.a+this.b;
}};
var p=Object.create(o);
p.a=1;
p.b=5;
console.log(p.f()); //6 调用原型链上的方法,原型链上的方法this指向对象的值



get/set方法与this
function modulus(){
return Math.sqrt(this.re*this.re+this.im*this.im);
}

var o={
re:1,
im:-1,
get phase(){
return Math.atan2(this.im,this.re);
}
};

Object.defineProperty(o,'modulus',{
get:modulus,enumberable:true,configurable:true
});
console.log(o.phase,o.modulus);



构造器中的this
例1:
function MyClass(){
this.a=37; //this指向原型为MyClass.prototype的空对象,如果没有return或者是return的是基本类型而不是一个对象,那么会将this作为返回值
}

var o=new MyClass();
console.log(o.a);

例2:
function C2(){
this.a=37;
return{a:38};
}

o=new C2();
console.log(o.a); //38



call/apply方法与this
function add(c,d){
return this.a+this.b+c+d;
}
var o={a:1,b:3};
add.call(o,5,7); //1+3+5+7=16
add.apply(o,[10,20]); //1+3+10+20=34
(这个有些不懂) function bar(){
console.log(Object.prototype.toString.call(this));
}
bar.call(7); //'[object Number]'



bind方法与this
例:
function f(){
return this.a;
}

var g=f.bind({a:'test'});
console.log(g()); //test

var o={a:37,f:f,g:g};
console.log(o.f(),o.g()); //37, test g方法还是按照绑定的属性返回



构造函数
例1
function Foo(){
this.name='jacob';
this.year=1988;
console.log(this); //Foo {name:"jacob",year:1988}, 只要该函数被实例化如下一行代码,那么就会显示Foo {name:"jacob",year:1988}
}
var f1=new Foo();
console.log(f1.name); //jacob
console.log(f1.year); //1988
以上代码中,如果函数作为构造函数使用,那么其中的this就代表它new出来的对象

注意,以上仅限new Foo()的情况,即Foo函数作为构造函数的情况。如果直接调用Foo函数,而不是new Foo(),情况就不大一样了
例2
function Foo(){
this.name='jacob';
this.year=1988;
console.log(this); //Window
}
Foo(); //这种情况this指向window



函数作为对象的一个属性
如果函数作为对象的一个属性时,并且作为对象的一个属性被调用时,函数中的this指向该对象
例1:
var obj={
x:10,
fn:function(){
console.log(this); //Object
console.log(this.x); //10
}
};
obj.fn();

如果fn函数不作为obj的一个属性被调用,会是什么结果?
例2:
var obj={
x:10,
fn:function(){
console.log(this); //Window
console.log(this.x); //undefined
}
};
var fn1=obj.fn;
fn1();
如上代码,如果fn函数被赋值到了另一个变量中,并没有作为obj的一个属性被调用,那么this就为window,this.x就为undefined



全局&调用普通函数
例1:
var x=10;
var fn=function(){
console.log(this); //window
console.log(this.s); //10
}
fn();

例2:
var obj={
x:10,
fn:function (){
function f(){
console.log(this);
console.log(this.x);
}
f();
}
};
obj.fn();
函数f虽然是在obj.fn内部定义的,但它仍然是一个普通函数,this指向window

猜你喜欢

转载自blog.csdn.net/weixin_39034984/article/details/80723326