箭头函数内的 this 指向外层的 this。 所以要知道箭头函数的 this 就得先知道外层 this 的指向,需要继续在外层应用七步口诀。 2. new 当使用 new 关键字调用函数时,函数中的 this 一定是 JS 创建的新对象。 读者可能会有疑问,“如果使用 new 关键调用箭头函数,是不是箭头函数的 this 就会被修改呢?”。 我们...
const obj = { name: 'Alice', regularFunction: function() { console.log(this.name); }, arrowFunction: () => { console.log(this.name); }};obj.regularFunction(); // 'Alice',this指向obj对象obj.arrowFunction(); // undefined,箭头函数的this指向在定义时确定,这里指向全局对...
regularFunction:function() { console.log(this.property1 +' '+this.property2); }, // Object中尽量不要使用箭头函数 arrowFunction: ()=> { console.log(this.property1 +' '+this.property2); } }; myObject.regularFunction();// 输出:Hello World myObject.arrowFunction();// 输出:undefined un...
箭头函数的this取值,规则非常简单,因为this在箭头函数中,可以看做一个普通变量。 An arrow function does not have its own this. The this value of the enclosing lexical scope is used; arrow functions follow the normal variable lookup rules. 箭头函数没有自己的this值,箭头函数中所使用的this都是来自函数...
newTarget正常调用下指向调用的function对象。比如foo(),newTarget就是foo,你可以在函数内部用new.target访问到。构造函数中的this对象与newTarget有关,如果newTarget.prototype存在,且是Object对象,则this就是ObjectCreate(newTarget.prototype),ObjectCreate是Object.create内部调用的方法,如果newTarget.prototype不存在或者...
constobj={name:'Alice',sayHi:()=>console.log(`Hello,${this.name}`)// this指向全局对象或undefined(严格模式)};// 应该使用普通函数或显式绑定thissayHi:function(){console.log(`Hello,${this.name}`);} 没有自己的arguments:箭头函数没有自己的arguments对象,使用剩余参数(...args)替代。
如果在某个函数内部定义箭头函数,那么这个箭头函数的this值就会绑定到外部函数的this值。 ⚠️ 外部函数的this是调用时绑定的,这意味着内部定义的箭头函数this也会跟着发生变化。 function outerFunction() { = "outerFunction"; let arrowFunction = () => { ...
就像上面讲的arrow function没有自身的this,当用call()或apply() 调用箭头函数时无法改变函数主体内的this。 示例: 代码语言:javascript 代码运行次数:0 运行 AI代码解释 // 普通函数varsayHello=function(userName){console.log('hi '+userName);console.log(this);};sayHello.call({x:1},'polk');// => ...
答案是:’汪‘ ,因为talk被调用时,this 上下文是 dog 对象 这边要强调的一点是 无论是场景一中 的cat.talk和 catTalkFunc 还是 场景二里的dog.talk其实并没有什么特别的处理 都只是同一个函数的引用即 function(){ console.log(this.sound); }
// an arrow function to add two numbersconstaddNumbers =(a, b) =>a + b;// call the function with two numbersconstresult = addNumbers(5,3);console.log(result);// Output: 8 Run Code In this example,addNumbers()is an arrow function that takes two parameters,aandb, and returns their...