原语上的 isPrototypeOf() 函数
isPrototypeOf() function on primitive
Mozilla.org 表示
The isPrototypeOf() method checks if an object exists in another object's prototype chain.
当我创建原始变量时,说
var a = 0;
并检查其 [[Prototype]](不是 a.prototype
),
console.log(a.__proto__); //on chrome
它打印 Number {0, isDivisibleBy2: ƒ, constructor: ƒ, toExponential: ƒ, toFixed: ƒ, …}
。显然,这个值似乎是 Number.prototype
.
里面的值
所以,我希望 Number.prototype.isPrototypeOf(a);
到 return 为真,因为 Number.prototype
确实存在于 a
的原型链中(__proto __ 链).
但是,Number.prototype.isPrototypeOf(a);
的输出是假的。
var a = 0;
console.log(a.__proto__);
console.log(Number.prototype);
console.log(Number.prototype === a.__proto__);
console.log(Number.prototype.isPrototypeOf(a));
我想我可能误解了什么...我相信 value.__proto__
是访问原型链的正确方法(从 this mozilla link 理解)。只是 isPrototypeOf()
对 primitive 不起作用吗?
谁能帮我弄清楚这个奇怪的现象?
JavaScript 实际上是在您访问其上的 属性 或调用方法时从原语创建一个新的 Number 对象,之后新对象会被迅速丢弃。这就是为什么您可以访问 __proto__
属性。但是,原语不是 Number 对象。
正如您在规范 here 中所见,isProtoTypeOf
的第一条规则是“如果 Type(V) 不是 Object,return false”(其中 V 是传递给方法的值)。
Mozilla.org 表示
The isPrototypeOf() method checks if an object exists in another object's prototype chain.
当我创建原始变量时,说
var a = 0;
并检查其 [[Prototype]](不是 a.prototype
),
console.log(a.__proto__); //on chrome
它打印 Number {0, isDivisibleBy2: ƒ, constructor: ƒ, toExponential: ƒ, toFixed: ƒ, …}
。显然,这个值似乎是 Number.prototype
.
所以,我希望 Number.prototype.isPrototypeOf(a);
到 return 为真,因为 Number.prototype
确实存在于 a
的原型链中(__proto __ 链).
但是,Number.prototype.isPrototypeOf(a);
的输出是假的。
var a = 0;
console.log(a.__proto__);
console.log(Number.prototype);
console.log(Number.prototype === a.__proto__);
console.log(Number.prototype.isPrototypeOf(a));
我想我可能误解了什么...我相信 value.__proto__
是访问原型链的正确方法(从 this mozilla link 理解)。只是 isPrototypeOf()
对 primitive 不起作用吗?
谁能帮我弄清楚这个奇怪的现象?
JavaScript 实际上是在您访问其上的 属性 或调用方法时从原语创建一个新的 Number 对象,之后新对象会被迅速丢弃。这就是为什么您可以访问 __proto__
属性。但是,原语不是 Number 对象。
正如您在规范 here 中所见,isProtoTypeOf
的第一条规则是“如果 Type(V) 不是 Object,return false”(其中 V 是传递给方法的值)。