[英]To assign a prototype to Number, should I use Function.prototype or Object.prototype?
I want to extend the type 'Number' with a new function and hence I have to define a prototype. 我想用新函数扩展类型'Number',因此我必须定义一个原型。 When I think about this, I get a bunch of questions:
当我想到这一点时,我会遇到很多问题:
1- True. 1-正确。
Number instanceof Object
returns true also Function instanceof Object
returns true. Number instanceof Object
返回true, Function instanceof Object
返回true。 So Number has all methods that Object and Function has. 因此,Number具有对象和函数所具有的所有方法。
2- Number is a function. 2-数字是一种功能。
typeof Number
returns "function". typeof Number
返回“函数”。
3- If you want to add a method to Number's prototype, just use 3-如果要向Number的原型添加方法,请使用
Number.prototype.METHOD_NAME = function() { // your logic }
Then you can call your method on all numbers like 1..METHOD_NAME()
然后,您可以对所有数字(例如
1..METHOD_NAME()
调用方法
The number methods are already contained in Number.prototype
to add own methods just do: 数字方法已经包含在
Number.prototype
可以添加自己的方法:
Number.prototype.addOne = function(){
return this.valueOf() + 1;
};
1..addOne() // 2
Your question confuses me as I am not sure whether by Number you mean the number constructor which is just an ordinary function or number primitives. 您的问题使我感到困惑,因为我不确定“数字”是指普通构造函数还是数字基元的数字构造函数。
Number primitives are not objects and as such don't inherit anything, when you do 1..addOne()
the number is converted to an object and then the .addOne
is found in the Number.prototype
and called with this
set to the object form of the number. 数元不是对象,因此不继承任何东西,当你做
1..addOne()
的数量转换为对象,然后.addOne
在发现Number.prototype
,并呼吁与this
组对象号码的形式。
Number
itself is an ordinary function. Number
本身是一个普通功能。
You can assign properties to it directly. 您可以直接为其分配属性。
If you want to extend number instances , you should assign to Number.prototype
. 如果要扩展数字实例 ,则应分配给
Number.prototype
。
I don't understand your questions. 我不明白你的问题。 If I really thought monkey-patching
Number
was a good idea, I'd just do: 如果我真的认为使用猴子补丁
Number
是个好主意,我会这样做:
Number.prototype.newfunc = function(...) { ... }
Number, Function and Object are all General-purpose constructors. Number,Function和Object都是通用构造函数。 Number inherit from Function which in turn inherits from Object.
Number从Function继承,而Function又从Object继承。 Number constructor should be used for number primitive to create wrapper object and invoke associated functions.
Number构造函数应用于Number Primitive创建包装对象并调用关联的函数。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.