var HOME = HOME || {};
HOME.sandBox = function ($) {
var result = function (coreObj) {
// this.coreObj = coreObj;
}
result.fn = result.prototype;
result.fn.each = function (arr, callback) {
arr.forEach(function (v, i) {
callback.call(v, i, v);
});
}
return new result();
}(jQuery)
HOME.sandBox.each([1, 2, 3, 4, 5], function (i, v) {
console.log(i, this, this.toString(), v); // 0 Number {[[PrimitiveValue]]: 1} "1" 1
console.log(this == v); // true
console.log(this === v); // false
});
上面的this和v是什么关系啊?[[PrimitiveValue]]这又是什么?
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号
首先JS中Number和number是两种不同的东西,number是原始类型,Number是其对应的封装类型是一个对象。
就像Java中的int和Integer的区别:
function里面的this,是一个对象
typeof this == 'object', 在你的方法中:你把v设置为callback的this,但是v是个number,所以自动类型转换发生了。
下面给你个演示,打开chrome控制台输入:
chrome控制台下输出:
其他类型:
至于null和undefined, 由于没有对应的封装类型(参见MDN),如果
t.call(null,null)或者t.call(undefined, undefined), JS引擎无法将null或undefined转换成对应的封装类型,就会把window对象设为t的this(chrome下是这样的,其他浏览器没有测试):