JavaScript中this關鍵字
阿新 • • 發佈:2018-11-10
JavaScript中this關鍵字用法較為靈活,用處較多,主要有以下幾種方式:
1.瀏覽器中,全域性的this指向window;
console.log(this===window);
console.log(this);
this.a='nice';
console.log(window.a);
驗證結果如下:
2.作為物件方法的函式this;
function sum(){ return this.x+this.y; } var obj={"x":1,"y":2}; obj.z=sum; console.log(obj.z()); var obj1={ x:1,y:2, z:function(){ return this.x*this.y; } } console.log(obj1); console.log(obj1.z());
驗證結果如下:
把函式作為物件屬性的值也稱作為物件的方法,this指向物件,該屬性可理解為需呼叫方法,使用時需加上().
3.物件原型鏈上的this;
var o={f:function(){
return this.x+this.y;
}}
var obj=Object.create(o);
obj.x=1;
obj.y=2;
console.log(obj.f());
驗證結果如下:
obj的原型是o,通過o的this關鍵字可以拿到當前物件obj,同時,obj的屬性f也可上溯至原型鏈o。
4. get/set方法與this;
var obj={
x:1,
y:2,
get z(){
return this.x**2+this.y**2;
}
};
function w(){
return Math.sqrt(this.x**2+this.y**2);
}
Object.defineProperty(obj,'w',{get:w,enumerable:true,configurable:true});
console.log(obj.z,obj.w);
驗證結果如下:
this可以得到當前物件,便於通過get給當前物件的屬性賦值.
5.構造器中的this;
function MyClass(){
this.a=35;
//無return關鍵字,則返回this;
}
var obj=new MyClass();
//使用new建立,則物件obj會指向MyClass.prototype.
console.log(obj.a);
驗證結果為:
this還有許多用到的地方,比如call,apply,bind方法,在此不一一列舉。可自行寫碼驗證。