2013-12-22 34 views

回答

8

var self = this在蘋果的頂部,然後將其稱爲自我,而不是在嵌套函數。

即:

Apple = function() { 
    var self = this; 
    this.price = 17 

    this.cutOpen = function() { 

     console.log(this.price); 
     countSeeds(); 

     function countSeeds() { 
      console.log(self.price); 
     } 
    }   
} 


var apple = new Apple(); 
apple.cutOpen(); 

你也可以把self=this聲明在this.cutOpen的開始,因爲這將仍然是指蘋果對象cutOpen(因爲它是蘋果的方法)。

更新

大多數常綠瀏覽器都支持箭頭的功能,所以你可以寫這樣的:

Apple = function() { 
    var self = this; 
    this.price = 17 

    this.cutOpen = function() { 

     console.log(this.price); 
     let countSeeds =() => { 
      console.log(this.price); 
     }; 
     countSeeds(); 
    }   
} 

這並不在IE11等舊版瀏覽器的工作,除非你使用某種的轉譯器來定位老的javascript。

+0

難道'countSeeds()'改變'this'變量本身? – Nyxynyx

+1

這個對象在一個函數的上下文中被設置爲三個中的一個:1.如果該函數是用新的(新的Apple)調用的,則這指的是將由構造函數返回的對象。 2.如果使用點語法(apple.cutOpen())或使用call或apply方法對某個對象調用該函數,則它指向該對象。 3.如果直接調用該函數(countSeeds()),那麼這指的是全局對象,它在瀏覽器中是窗口。 – Thayne

+1

您忘記了'.call()','.apply()','.bind()',這是括號語法,相當於點符號和(即將標準化的)箭頭函數。要記住的重要一點是執行上下文的'this'綁定是通過調用函數的方式來定義的。 –

1

默認情況下,當您在不提供上下文的情況下調用函數時,this指的是window對象。嘗試callapply設置上下文,如果你不喜歡默認:

this.cutOpen = function() { 

     console.log(this.price); 
     countSeeds.call(this); //use call to set the context for the function. 

     function countSeeds() { 
      console.log(this.price); 
     } 
    } 

我建議你移動的構造函數外防止它被重新定義了多次:

function countSeeds() { 
      console.log(this.price); 
     } 

Apple = function() { 
    this.price = 17 

    this.cutOpen = function() { 

     console.log(this.price); 
     countSeeds.call(this); 
    }   
} 

或定義爲原型的功能:

Apple = function() { 
     this.price = 17 

     this.cutOpen = function() { 

      console.log(this.price); 
      this.countSeeds(); //use countSeeds as an instance method. 
     }   
    } 

    Apple.prototype.countSeeds = function() { 
      console.log(this.price); 
    } 

在我看來,countSeeds在這種情況下,應該是一個實例方法它總是訪問當前實例的price財產和不能工作如果thiswindow