gpt4 book ai didi

javascript - javascript中的原型(prototype)继承

转载 作者:行者123 更新时间:2023-11-29 10:42:53 25 4
gpt4 key购买 nike

我从 Javascript Good Parts 一书中获取了以下示例,并在 firefox 中运行它:

Function.prototype.method = function(name, value){
this.prototype[name] = value;
return this;
}

Number.method('integer', function ( ) {
return Math[this < 0 ? 'ceil' : 'floor'](this);
});

console.log((-10 / 3).integer());

这是我对其工作原理的理解。我们使用 () 高优先级运算符计算 -10/3,它给出了这个 64 位浮点值 -3.3... 由于 JavaScript 没有 Float、Decimal 或 Integer 类型,因此返回值是 Number。因此,我们在其原型(prototype)链中的 Number 对象上调用函数 integer()。 “this”必须引用 Number 对象持有的值。我们使用三元来检查它是负数还是正数,在这种情况下我们运行: Math'ceil' 因为它是负数。这会将数字向上舍入以产生 -3。

这个脚本可以工作,但我不明白为什么 Number.method 没有抛出异常,因为 Number 不是 Function 的一种类型,方法是在 Function 的原型(prototype)上定义的,而不是 Number 的原型(prototype),而 Number 没有不是继承自Function,它只是继承自Object.prototype。

最佳答案

在您的控制台中尝试这些示例

Number 是一个函数。

typeof Number
"function"

确认。

因此,Number 确实继承自 Function

Number instanceOf Function
"true"

Function 一样,像所有其他 JavaScript 对象一样,继承自 Object

Function instanceof Object
true

关于javascript - javascript中的原型(prototype)继承,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25344144/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com