只是好奇:
- 4 instanceof Number => false
- new Number(4) instanceof Number => true?
为什么是这样?与字符串相同:
'some string' instanceof String
返回假new String('some string') instanceof String
=> 真String('some string') instanceof String
也返回假('some string').toString instanceof String
也返回假
对于对象、数组或函数类型,instanceof 运算符按预期工作。我只是不知道如何理解这一点。
[新见解]
Object.prototype.is = function() {
var test = arguments.length ? [].slice.call(arguments) : null
,self = this.constructor;
return test ? !!(test.filter(function(a){return a === self}).length)
: (this.constructor.name ||
(String(self).match ( /^function\s*([^\s(]+)/im )
|| [0,'ANONYMOUS_CONSTRUCTOR']) [1] );
}
// usage
var Newclass = function(){}; // anonymous Constructor function
var Some = function Some(){}; // named Constructor function
(5).is(); //=> Number
'hello world'.is(); //=> String
(new Newclass()).is(); //=> ANONYMOUS_CONSTRUCTOR
(new Some()).is(); //=> Some
/[a-z]/.is(); //=> RegExp
'5'.is(Number); //=> false
'5'.is(String); //=> true