--为了取代var self = this; 或.bind(this),以一种更便捷和巧妙的方式来从外部函数继承this In other words, arrow functions treat this like any other lexical variable. 翻译:换句话说,箭头函数对待this就像对待任何其他词法变量一样 If you use a this insid
在嵌套函数中使用箭头函数可以保持外层的 this 上下文。 function outerFunction() { this.outerValue = "I am from the outer function"; function innerRegularFunction() { console.log(this.outerValue); // undefined,因为这里的 this 不指向 outerFunction 的实例 } const innerArrowFunction = () => { ...
f是箭头函数,箭头函数没有this,它的this是绑定了父作用域(全局作用域)上下文,父作用域的a="hi",所以输出hi。 通过babel编译一下,更能看出箭头函数的本质,能很直观的看出箭头函数的this绑定的事父作用域。 var _this = void 0; var obj = { f: function f() { console.log(_this.a); } }; (void ...
let sum = (a, b) => a + b; /* This arrow function is a shorter form of: let sum = function(a, b) { return a + b; }; */ alert( sum(1, 2) ); // 3 上述的例子在中,在等号的右边,箭头函数计算了a+b的值,并返回该值。需要注意的是,这里赋值给sum的是函数本身,而不是函数...
function func() { console.log(this, this.__proto__ === func.prototype) } boundFunc = func.bind(1) new boundFunc() // Object true,口诀 2 优先 1. 2. 3. 4. 5. 6. 4. apply 和 call apply()和call()的第一个参数都是 this,区别在于通过 apply 调用时实参是放到数组中的,而通过 cal...
title =`arrow function`;log(`this.name`,this.name); };log(`\nfunc`, func);log(`\nfunc.prototype`, func.prototype);// func.prototype undefined// 2. prototype bugfunc.prototype.print=function() {letname =this.name;log(`\nname =`, name); ...
functiona() {console.log("function a:",this) ;(() =>{console.log("arrow function: ",this) })() }a() a.bind(null)() a.bind(undefined)() a.bind().bind(2)() a.apply() 非严格模式下执行结果为: 在严格模式下,执行同样的代码进行对比。记住要一次性将所有代码复制粘贴到控制台中,才能...
箭头函数的this指向在其定义时所在的上下文中的this。即使作为对象的属性值,箭头函数的this依旧指向定义时的上下文。例如:(function() { const arrowfunc = () => console.log(this) console.log('-- 外层作用域 --'); console.log(this); // String {'hello'} arrowfunc(); // String {...
箭头函数没有自己的this 与常规函数不同,箭头函数没有自己的this和参数绑定。相反,这些标识符像任何其他变量一样在词法范围内解析。让我们看一个简单的例子: name="Arrow function" letme={ name:"Regular function", thisInArrow:()=>{ console.log("Example of "+this.name);//无 'this' 绑定 ...
代码没有在任何函数中执行,而是在全局作用域中执行时,this 的值就是 global 对象,对于浏览器来说,this 就是 window。 这一条规则还是比较容易接受的。 Function context Inside a function, the value of this depends on how the function is called. ...