gpt4 book ai didi

javascript - 为什么我们不能使用 delete 运算符删除 javascript 中的函数?

转载 作者:行者123 更新时间:2023-11-29 21:07:48 25 4
gpt4 key购买 nike

var sum = function(a, b) {return a + b;};

var add = sum;

delete sum;

执行删除后,它在控制台中返回 False。理想情况下,它应该返回 True。为什么sum函数没有被删除?

注意上面的代码是在 google chrome 浏览器控制台中执行的。

最佳答案

来自 MDN :

The delete operator removes a given property from an object.

If the property which you are trying to delete does not exist, delete will not have any effect and will return true.

If a property with the same name exists on the object's prototype chain, then, after deletion, the object will use the property from the prototype chain (in other words, delete only has an effect on own properties).

Any property declared with var cannot be deleted from the global scope or from a function's scope.

As such, delete cannot delete any functions in the global scope (whether this is part from a function definition or a function expression).

Functions which are part of an object (apart from the global scope) can be deleted with delete.

因此 sum 是一个附加到全局范围的函数,不能用 delete 删除。

关于javascript - 为什么我们不能使用 delete 运算符删除 javascript 中的函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43164913/

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