确定对象包装的基元是否是用户创建的

时间:2015-04-20 01:28:19

标签: javascript primitive

var obj = {x:5, y:new Number(5)};

function value(value) {
    //using == would result in false positives for value.call(obj.y, new Number(5));
    return this === value;
}

console.log(value.call(obj.x, obj.x)); //False
console.log(value.call(obj.y, obj.y)); //True

Javascript(出于显而易见的原因),在将基元分配给this时将它们包装在临时对象中。有没有办法确定通过this引用的对象是用户创建的还是永久对比系统创建和瞬态?

1 个答案:

答案 0 :(得分:0)

你可以试试这个:

function fun() {
    // in browser, the 'global' is window, and global in node.
    // but in strict mode, if you don't specify 'this', it will be 'undefined'.
    if (this === global || this === undefined) {
        console.log('system created');
    } else {
        console.log('user created');
    }
}