How Javascript Realizes Extended Basic Types

  • 2021-08-09 06:54:03
  • OfStack

You can make this method available to all functions by adding a method to Function. prototype.

By adding an method method to Function. prototype, you don't have to type the characters prototype the next time you add a method to an object.


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

1. JavaScript Adding Integer Types

JavaScript does not have a specific integer type, but sometimes it does require only the integer part of the number to be advanced.

You can add an integer method to Number. prototype.

The inter () method determines whether to use Math. ceiling or Math. floor based on the positive and negative numbers.


Number.method('integer',function(){
  return Math[this<0?'ceil':'floor'](this);
});
document.writeln((-10/3).integer());//-3

2. JavaScript is missing a method to remove white space at the beginning and end of a string


String.method('trim',function(){
  return this.replace(/^\s+|\s+$/g,'');
});

document.writeln(' " '+"  neat  ".trim() +' " ');//" neat "

Prototypes of basic types are common structures, so care must be taken when mixing class libraries. An insurance approach is to add it only when it is determined that there is no such method.


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

new prefix to call 1 function


Function.method('new',function () {
  // Create 1 A new object that inherits from the prototype object of the constructor function. 
  var that=Object.create(this.prototype);
  // Call the constructor function, bind -this- To a new object. 
  var other=this.apply(that,arguments);
  // If its return value is not 1 Object, the object is returned. 
  return (typeof other==='object'&&other)||that;
});

superior


Object.method('superior',function(name){ // Pass in the method name name
  var that=this,method=that[name]; 
  return function(){
    return method.apply(that,argumetns);
  }
});

Related articles: