2012-08-05 14 views
1

我找不到原因,這不起作用:申請方法不起作用在畫布上上下文了lineTo()

var c=document.getElementById("myCanvas"), 
ctx=c.getContext("2d"); 
ctx.moveTo(0,0); 
ctx.lineTo.apply(this, [100, 100]); 
ctx.stroke(); 
+2

你期望'這個'在這裏? – xdazz 2012-08-05 11:25:05

+0

你預計會發生什麼?到底發生了什麼?你是否收到任何錯誤訊息?你到目前爲止已經嘗試過什麼來解決這個問題? – PPvG 2012-08-05 12:03:00

+0

@xdazz - 我預計畫一條線。 – Luckylooke 2012-08-06 10:58:07

回答

2

眼下,this要麼window ......這真的不知道該怎麼使用.lineTothis是任何對象擁有此代碼包裝的功能。

如果此代碼未包含在函數中(或者即使它是,如果該函數不是某個函數的屬性對象,this === window)。

如:

MyObj.myFunc = function() { 
    var c = document.getElementById("myCanvas"), 
    // ..........etc 
    ctx.lineTo.apply(this, [100,100]); 
}; 

該代碼將使用MyObj作爲this調用.lineTo
如果MyObj不知道如何處理該信息,或者.lineTo找不到需要附加到MyObj的屬性,那麼它將失敗。

在幾乎所有其他從this中讀取的情況下,代替寫入它,this指的是window

另一個常見的陷阱:函數內部的函數。

MyObj = { 
    name : "Bob", 
    sayName : function() { 
     console.log(this.name); // works -- "this"===MyObj 
     var say_it_again = function() { 
      console.log(this.name + ", for the second time"); 
     }; 
     say_it_again(); 
     // second function doesn't work -- "this"===window 
}; 

爲了範圍this正確在這種情況下,將其保存爲在所述第一函數的變量,並且在第二引用它。

MyObj = { 
    name : "Bob", 
    sayName : function() { 
     var person = this; // now the reference to "this" is kept in "person" 
     console.log(this.name); // works -- "this"===MyObj 
     var say_it_again = function() { 
      console.log(person.name + ", for the second time"); 
     }; 
     say_it_again(); 
     // works -- "person" refers to the saved variable in the first function 
     // that variable happens to hold a reference to "this" from the first function 
     // which happens to be MyObj 
}; 
3

好的,我在你的答案後讓它有效,謝謝。我認爲這指向了ctx變量。

var c=document.getElementById("myCanvas"), 
ctx=c.getContext("2d"); 
ctx.moveTo(0,0); 
ctx.lineTo.apply(ctx, [100, 100]); 
ctx.stroke(); 

謝謝,再見;)

0

lineTo取決於this對象是上下文

通常情況下你怎麼稱呼它爲ctx.lineTo(...),含蓄地設置this=ctx

但是當你使用.apply,你可以選擇覆蓋this

如果您說....lineTo.apply(this, ...)您將this設置爲範圍內發生的任何事情(通常是window對象,或者其他使用點符號的東西)。

因此做.....lineTo.apply(ctx, ...)