gpt4 book ai didi

Javascript 调用改变类型

转载 作者:行者123 更新时间:2023-11-30 09:02:53 24 4
gpt4 key购买 nike

我想分别编写一个类似 jQuery 的函数,并且正在使用 javascript 调用函数。

function each(array, callback) {
for (var i=0; i<array.length; i++) {
console.log(typeof(array[i])); // Number
callback.call(array[i]);
}
}

each([1,2,3], function() {
console.log(typeof(this)); // Object
});

问题是调用似乎将数字类型转换为对象类型。这会导致 console.log 调用出现问题。谁能解释为什么会这样(我的猜测是调用将参数转换为 Object 类型)。它为什么要这样做?你能想出一种解决或防止这种情况的方法吗?

最佳答案

当不处于严格模式时,这是规范的要求。

如果您在代码顶部使用 "use strict"; 声明,您将获得您传递的任何实际值。

演示: http://jsfiddle.net/agXkZ/

"use strict";
function each(array, callback) {
for (var i=0; i<array.length; i++) {
callback.call(array[i]);
}
}

each([1,2,3], function() {
console.log(this);
});

请注意,严格模式是词法范围的,因此您可以仅在愿意时将声明添加到回调中。

演示: http://jsfiddle.net/agXkZ/1/

function each(array, callback) {
for (var i=0; i<array.length; i++) {
callback.call(array[i]);
}
}

each([1,2,3], function() {
"use strict";
console.log(this);
});

如果您不想使用严格模式,您可以(在这种情况下)使用一元 + 运算符转换为原语。

演示: http://jsfiddle.net/agXkZ/2/

function each(array, callback) {
for (var i=0; i<array.length; i++) {
callback.call(array[i]);
}
}

each([1,2,3], function() {
console.log( +this ); // <--converts from object to primitive
});

相关信息:

来自 ECMAScript 5 Annex E (informative) Additions and Changes in the 5th Edition that Introduce Incompatibilities with the 3rd Edition :

15.3.4.3, 15.3.4.4: In Edition 3 passing undefined or null as the first argument to either Function.prototype.apply or Function.prototype.call causes the global object to be passed to the indirectly invoked target function as the this value. If the first argument is a primitive value the result of calling ToObject on the primitive value is passed as the this value. In Edition 5, these transformations are not performed and the actual first argument value is passed as the this value...

ECMAScript 5 Annex C (informative) The Strict Mode of ECMAScript :

If this is evaluated within strict mode code, then the this value is not coerced to an object. A this value of null or undefined is not converted to the global object and primitive values are not converted to wrapper objects. The this value passed via a function call (including calls made using Function.prototype.apply and Function.prototype.call) do not coerce the passed this value to an object.

关于Javascript 调用改变类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7786843/

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