Create a new number method that returns a number's half value:
Number.prototype.myMethod = function() {
return this.valueOf() / 2;
};
Use the new method on a number:
let n = 55;
let x = n.myMethod();
Try it Yourself »
prototype
allows you to add new properties and methods to numbers.
prototype
is a property available with all JavaScript objects.
Number.prototype.
name =
value
You are not advised to change the prototype of an object that you do not control.
You should not change the prototype of built in JavaScript datatypes like:
Only change the prototype of your own objects.
The JavaScript prototype
property allows you to add new properties to objects:
function Person(first, last, age, eyecolor) {
this.firstName = first;
this.lastName = last;
this.eyeColor = eyecolor;
}
Person.prototype.nationality = "English";
Try it Yourself »
Number.prototype
is an ECMAScript1 (ES1) feature.
ES1 (JavaScript 1997) is fully supported in all browsers:
Chrome | Edge | Firefox | Safari | Opera | IE |
Yes | Yes | Yes | Yes | Yes | Yes |
截取页面反馈部分,让我们更快修复内容!也可以直接跳过填写反馈内容!