2011-11-09 113 views
2

您好我需要改變鼠標移動財產的OnMouseMove但我不能訪問MYFUNC對象,因爲這EL沒有父!訪問父母的財產

function myfunc (el) { 
    this.el = el; 
    this.mousemove = false; 

    el.onmousemove = function(){ 
     this.mousemove = true; 
    }; 
} 
+0

父母是誰? – nico

+1

'myfunc'的範圍。讓我們找到一個重複的。 –

+0

父母是myfunc –

回答

5

只要存儲對this的引用,就可以隨意調用它。這是常見的使用thatself

function myfunc(el) { 
    var that; 
    that = this; 
    this.el = el; 
    this.mousemove = false; 
    el.mousemove = function() { 
    that.mousemove = true; 
    }; 
} 
1

一種方法是創建相關this參考;例如

function myfunc (el) { 
    this.el = el; 
    this.mousemove = false; 

    var t=this; 
    el.onmousemove = function(){ 
     t.mousemove = true; 
    }; 
} 
1

取出this的,因爲它們都指牛逼window

function myfunc (el) { 
    var mousemove = false; //scoped 

    el.onmousemove = function(){ 
     mousemove = true; //same scoped variable 
    }; 
} 
+0

如果myfunc在聲明後被分配給對象或原型,則不會。 – zzzzBov

1

這聽起來像你想的mousemove值從onmousemove處理程序發生改變。如果是這樣,則需要將原始上下文捕獲到您稍後可以訪問的值中。例如

function myfunc (el) { 
    this.el = el; 
    this.mousemove = false; 
    var self = this; 

    el.onmousemove = function(){ 
     self.mousemove = true; 
    }; 
}