var objReg = { hello: function() { return this; } }; var objArrow = { hello: () => this }; objReg.hello(); // returns the objReg object that we expect objArrow.hello(); // returns the Window object! 根据MDN的定
正如MDN文档所说: Until arrow functions, every new function defined its own this value based on how the function was called。This proved to be less than ideal with an object-oriented style of programming. 箭头函数 箭头函数的this取值,规则非常简单,因为this在箭头函数中,可以看做一个普通变量。 An ...
“this”是 JavaScript 的一个关键字,它具体的含义依赖于使用的环境。 至于在学习 JavaScript 的时候,”this”如此让人迷惑就是因为它的环境又基于你如何使用它。 你甚至可以把它理解成为一个动态的关键字。 我很喜欢 Ryan Morr 在Understanding Scope and Context in JavaScript中的一句话: Context is always the ...
function checkAge(age) { if (age < 18) { throw new Error("Age must be 18 or older."); } return "Access granted."; } Day 25: Modules - import and export Topics: Using import and export for Modules Description: Learn how to work with JavaScript modules. Code Example: // export.js...
正如MDN文档所说: Until arrow functions, every new function defined its own this value based on how the function was called。This proved to be less than ideal with an object-oriented style of programming. 箭头函数 箭头函数的this取值,规则非常简单,因为this在箭头函数中,可以看做一个普通变量。
This leads to three errors in our code. // First, we’re adding properties to this in the constructor function. Again, because Arrow Functions don’t have their own this, you can’t do that. // Second, we can’t use the new keyword with an Arrow Function. This will throw a X is...
// Create obj with a method bar that returns a function that // returns its this. The returned function is created as // an arrow function, so its this is permanently bound to the // this of its enclosing function. The value of bar can be set // in the call, which in turn sets...
关于this 的文章也够多了,有时候越描越黑,我就不再添乱了,我只负责搬运一下 MDN 文档:this,感兴趣的可以仔细阅读一下,我摘录一些最重要的话就好了。 A function’s this keyword behaves a little differently in JavaScript compared to other languages. It also has some differences between strict mode and...
Every function has the method.bind[docs], which returns a new function withthisbound to a value. The function has exactly the same behavior as the one you called.bindon, only thatthiswas set by you. No matter how or when that function is called,thiswill always refer to the passed value...
C: Function expressions with grouping operators: var C = (function(){}); These really aren’t different from plain old function expressions and aren’t really seen in the wild (so maybe they’re just good for JavaScript quizzes?). Recently this way of declaring functions was brought up ...