函数直接调用和通过对象属性obj.myFunc()是不同的,它叫做方法调用method invocation(后边介绍的第2种类型)。比如[1,5].join(',')这种不是一个函数直接调用,而是方法调用。这两种是最容易混淆的,需要特别注意。 此外,一个IIFE(immediately-invoked function expression)也属于函数直接调用。 代码语言:javascript 代码...
但在JavaScript 中情况就比较复杂了:this 指向当前函数调用的执行上下文(context),有四种函数调用类型: 函数直接调用(function invocation:alert('Hello World!') 方法调用(method invocation:console.log('Hello World!') 构造函数调用(constructor invocation:new RegExp('\\d') 间接调用(indirect invocation:alert.ca...
sayHi; carSayHi(); // TypeError because the 'sayHi' method tries to access 'this.name', but 'this' is undefined in strict mode. 然而,请注意,自动绑定的方法遭受的问题与使用箭头函数作为类属性相同:类的每个实例都会有其方法的自己的副本,这会增加内存使用。只在绝对必要的地方使用它。你也可以模仿 ...
In JavaScript, thethiskeyword refers to an object. Which object depends on howthisis being invoked (used or called). Thethiskeyword refers to different objects depending on how it is used: In an object method,thisrefers to the object. Alone,thisrefers to the global object. In a function,t...
method.call( newThisContext, Param1, ..., Param N ) method.apply( newThisContext, [ Param1, ..., Param N ] ); 再看一个复杂一点的代码案例: <!DOCTYPE html> Changing Execution Context In JavaScript //Create a global variable for...
JavaScript 的 this 原理 一、问题的由来 学懂JavaScript 语言,一个标志就是理解下面两种写法,可能有不一样的结果。 varobj={foo:function(){}};varfoo=obj.foo;// 写法一obj.foo()// 写法二foo() 上面代码中,虽然obj.foo和foo指向同一个函数,但是执行结果可能不一样。请看下面的例子。
method: function () { console.log(this); } }; parent.method(); // <- parent 注意这种行为非常“脆弱”,如果你获取一个方法的引用并且调用它,那么this的值不会是parent了,而是window全局对象。这让大多数开发者迷惑。 var parentless = parent.method; ...
In the above example,thisrefers to thepersonobject. 5. this Inside Inner Function When you accessthisinside an inner function (inside a method),thisrefers to the global object. For example, constperson = {name:'Jack',age:25,// this inside method// this refers to the object itselfgreet(...
JavaScript中关于this的一个bug 让我们更进一步延伸来看这个范例: 假设我们在method log裡面多这一行this.name = "Updated Object C name" 因为我们知道”this”现在指的是对象c,所以可以想像的,当我执行这个method的时候,它会去变更c.name的值。 这个部分是没有什么大问题的,不过让我们继续看下去……。
this是 JavaScript 语言的一个关键字。 它是函数运行时,在函数体内部自动生成的一个对象,只能在函数体内部使用。 functiontest(){this.x=1;} 上面代码中,函数test运行时,内部会自动有一个this对象可以使用。 那么,this的值是什么呢? 函数的不同使用场合,this有不同的值。总的来说,this就是函数运行时所在的环...