js 中的this是比較難了解的。這裡将介紹this的具體用法。主要是下面的四種方法:
1.作為對象的方法;
2.作為普通函數中;
3.作為構造函數調用;
4.作為Function.prototype.call或者Function.prototype.apply調用;
一、作為對象的方法使用,this指向這個對象;
For Example:
var adou = {
a:1,
getAdou: function() {
console.log( this===adou );//true
console.log( this.a );//1
}
}
adou.getAdou();
二、作為普通函數調用,this,指向全局變量window (浏覽器中)
For Example:
window.a = "adou";
function getAd(){
console.log(this.a);//adou
}
getAd();
在舉一個容易混淆的函數例子:
For Example2:
window.a = "adou";
console.log( this.a );//adou
}
var adouTwo = adou.getAdou;//将adou的getAdou方法指派給了adouTwo後,
//adouTwo就是一個普通函數,在調用這個普通函數時候,this指向的就是全局變量
adouTwo();
三、作為構造函數調用,this的指向是 往下看
構造函數和普通函數差不多一樣的。但是在與調用方式 new的差別(new的具體解析下回分解),當用 new 運算符調用函數時,該函數會傳回一個對象。一般情況下,構造器裡面的this就是指向傳回的這個對象。
For Example:
function Ad(){
this.a = "adou";
var adou = new Ad();
console.log(adou.a);//adou
但是,如果構造器函數顯示的傳回一個object類型的對象,new運算最終的結果會傳回這個對象;
For Example2:
function Ad(){
return {
a : "Bob"
var ad = new Ad();
console.log(ad.a);//Bob
四、 Function.prototype.call 或 Function.prototype.apply 調用 this是指: 往下看
這裡簡單的說call和apply這個方法:一個對象調用另一個對象的成員函數或屬性等。在調用call(apply)的時候。可以動态傳入 this ,這個this就是我們最終要操作的對象
var ad1 = {
name : "adou",
getName : function(){
console.log(this.name)
}
var ad2 = {
name : "adou2"
}
ad1.getName();//adou
ad1.getName.call(ad2);//adou2
下方的this 如下:
<script>
var tree = {};
tree.decorate = function () {console.log(333)}
tree.getdeco = function (deco) {
console.log(this,deco)
tree[deco].prototype = this;
return new tree[deco]
}
tree.redBalls = function(){
console.log('1',this);
this.decorate = function (){
console.log('2',this)
this.redBalls.prototype.decorate();
console.log('這是一個decorate')
}
}
tree = tree.getdeco('redBalls');
tree.decorate()
</script>