JS使用call后的疑问

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

});

上面的thisv是什么关系啊?[[PrimitiveValue]]这又是什么?

阅读 2.5k
1 个回答

首先JS中Number和number是两种不同的东西,number是原始类型,Number是其对应的封装类型是一个对象。
就像Java中的int和Integer的区别:

var a = 1;
console.log(typeof a);
输出:number
var b = new Number(1);
console.log(typeof b)
输出:Number
console.log(b);
输出:Number {[[PrimitiveValue]]: 1}

function里面的this,是一个对象 typeof this == 'object', 在你的方法中:

callback.call(v, i, v);

你把v设置为callback的this,但是v是个number,所以自动类型转换发生了。

下面给你个演示,打开chrome控制台输入:

function t(a) {
    console.log(this);
    console.log(a);
    console.log(a == this);
    console.log(a === this);
    console.log(typeof this);
    console.log(typeof a)
};
t.call(1,1);

chrome控制台下输出:

VM791:2 Number {[[PrimitiveValue]]: 1}   // this
VM791:2 1                                // a
VM791:2 true                             // a == this
VM791:2 false                            // a===this
VM791:2 object                           // typeof this
VM791:2 number                           // typeof a

其他类型:

t.call(true,true)
Boolean {[[PrimitiveValue]]: true}
VM132:2 true
VM132:2 true
VM132:2 false
VM132:2 object
VM132:2 boolean

t.call('1','1')
String {0: "1", length: 1, [[PrimitiveValue]]: "1"}
VM132:2 1
VM132:2 true
VM132:2 false
VM132:2 object
VM132:2 string

至于null和undefined, 由于没有对应的封装类型(参见MDN),如果t.call(null,null)或者t.call(undefined, undefined), JS引擎无法将nullundefined转换成对应的封装类型,就会把window对象设为tthis(chrome下是这样的,其他浏览器没有测试):

t.call(null, null);
VM132:2 Window {top: Window, location: Location, document: document, window: Window, external: Object…}
VM132:2 null
VM132:2 false
VM132:2 false
VM132:2 object
VM132:2 object
撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题