我找不到这不起作用的原因:
var c=document.getElementById("myCanvas"),
ctx=c.getContext("2d");
ctx.moveTo(0,0);
ctx.lineTo.apply(this, [100, 100]);
ctx.stroke();
我找不到这不起作用的原因:
var c=document.getElementById("myCanvas"),
ctx=c.getContext("2d");
ctx.moveTo(0,0);
ctx.lineTo.apply(this, [100, 100]);
ctx.stroke();
好的,我在你回答后让它工作,谢谢。我认为 THIS 指向 ctx 变量。
var c=document.getElementById("myCanvas"),
ctx=c.getContext("2d");
ctx.moveTo(0,0);
ctx.lineTo.apply(ctx, [100, 100]);
ctx.stroke();
谢谢再见 ;)
现在,this要么是window... 真的不知道如何处理.lineTo,要么this是任何对象拥有包含此代码的函数。
如果此代码未包含在函数中(或者即使是,如果该函数不是对象的属性,this=== window)。
例如:
MyObj.myFunc = function () {
var c = document.getElementById("myCanvas"),
// ..........etc
ctx.lineTo.apply(this, [100,100]);
};
该代码将.lineTo调用MyObjas this。
如果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
};
lineTo取决于this作为上下文的对象
通常你称它为ctx.lineTo(...),隐式设置this=ctx
但是,当您使用 时.apply,您可以选择覆盖this
如果您说....lineTo.apply(this, ...)您要设置this为范围内的任何内容(通常是window对象,或者如果您使用点表示法,则为其他内容)。
因此做.....lineTo.apply(ctx, ...)