Skip to main content
 首页 » 编程设计

javascript之闭包中的箭头函数

2025年05月04日12lyj

为什么这有效:

var a = () => {  
 
    var print = function(i) { console.log(i); return this; }     
    var print2 = function(i) { console.log(i); return this; } 
 
    return { print:print , print2:print2 } 
} 
 
a().print(5).print2(5); 

这也有效:

var b = () => {  
 
    var print = (i) => { console.log(i); return this; }     
    return { print:print} 
} 
b().print('Arrow function works'); 

虽然这不起作用:

var b = () => {  
 
    var print = (i) => { console.log(i); return this; }     
    var print2 = function(i) { console.log(i); return this; } 
 
    return { print:print , print2:print2 } 
} 
b().print(5).print2(5); 

https://jsfiddle.net/Imabot/1gt2kxfh/14/

请您参考如下方法:

这都是由于箭头函数的行为( docs )

分步说明:

var b = () => {  
    // 1 
    var print = (i) => { console.log(i); return this; }     
    var print2 = function(i) { console.log(i); return this; } 
 
    return { print:print , print2:print2 } 
} 
const res = b() 
// 2 
const secondRes = res.print(5) 
// 3 
secondRes.print2(5);

  1. 此处 print 函数保存来自外部作用域的 this 引用,因此 this 无法再重新分配
  2. 现在 print 函数未使用来自 res 变量的 this 引用,因为 this 已经附加到上面的 print 函数
  3. 因此,secondRes 不会引用 b 函数返回的对象。但它将使用附加到 print 函数的 this 引用。最后,因为 secondRes 没有 print2 属性 - 它会抛出

希望对你有帮助<3