gpt4 book ai didi

javascript - 对 JS 中的执行上下文感到困惑

转载 作者:行者123 更新时间:2023-11-30 15:06:17 24 4
gpt4 key购买 nike

// Replace the method named m of the object o with a version that logs
// messages before and after invoking the original method.
function trace(o, m) {

// Remember original method in the closure
var original = o[m];

// Define the new method
o[m] = function() {

// Log message
console.log(new Date(), "Entering:", m);

// Invoke original
var result = original.apply(this, arguments);

// Log message
console.log(new Date(), "Exiting:", m);

return result;
};
}

您好!上面给出的代码示例来 self 的编码书。它尝试使用 JavaScript 中的 apply 函数来说明一种称为“猴子修补”的做法。我真的很困惑调用原始函数的行的性质:

var result = original.apply(this, arguments); // Invoke original.

据我所知,对原始函数的调用也可以在没有 apply() 帮助的情况下编写,因为 thisarg 是 this,这是为了假设执行上下文保持不变:原始对象。

第二个混淆点是 apply()argumentsargument 到底从哪里来的?是的,我知道它是在每次函数调用时生成的对象,用于访问函数参数——但这一行是在一个没有任何参数的匿名函数中。我没有任何线索,非常感谢任何提示。

提前致谢!

最佳答案

您的第一个问题:为什么需要apply

如果在匿名函数中直接调用originaloriginal里面的this肯定是指global (undefined 在严格模式下)。另一方面,匿名函数被声明为 o 的方法,因此如果您调用 o.m()this 在匿名函数应该引用o。需要将 o 传递给 original,因为它保留了语义。

除了绑定(bind) this 之外,apply 还可以将参数数组转换为单个参数。

function toBeCalled(x,y){
console.log('x is: '+x+" y is:"+y)
}

function x (){
toBeCalled(arguments)
toBeCalled.apply(this,arguments)
}

x('aa','bb','vv')

//x is: [object Arguments] y is:undefined
//x is: aa y is:bb

看出区别了吗?

第二个问题:arguments从哪里来?

在 JavaScript 中,arguments 是函数范围内的内置变量。 arguments 的值只能在函数被调用时确定,根本不固定。

function x (){
console.log(arguments)
}

x('aa','bb','vv')
x("ff","dd")
x(1123)

argumentsx 被调用时被赋值,它是动态的。

关于javascript - 对 JS 中的执行上下文感到困惑,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45703214/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com