JavaScript - String.newProperty vs. String.prototype.newProp

JavaScript - String.newProperty vs. String.prototype.newProperty?

本文关键字:String prototype newProp vs newProperty JavaScript      更新时间:2023-09-26

在http://jsfiddle.net/javascriptenlightenment/QvbDw/,作者用两个新属性扩充了内置的String对象构造函数——一个数组属性和一个函数属性。

我注意到,对于新的数组属性,他这样做了:

String.newArrayProperty = [];
// Q1: Why not String.prototype.newArrayProperty = []; ?

但对于新的函数属性,他这样做了:

String.prototype.newFunctionProperty = function() {...};
// Q2: Why not String.newFunctionProperty = function() {...}; ?

String.newProperty和String.prototype.newProperty之间有什么区别?

String.newPropertyString本机函数添加了一个新属性,但该属性不会被它生成的字符串继承,而String.prototype.newProperty将该新属性添加到它生成的所有字符串中,但不会添加到本机函数本身。

String.property只是将properyString类作为对象进行广告,String.prototype.property将此属性添加到该类的所有实例中。

function F() {
}
F.p1 = function () { console.log('F.p1'); } ;
F.prototype.p2 = function () { console.log('F.prototype.p2'); } ;
F.p1(); // 'F.p1'
F.p2(); // error
new F().p1(); // error
new F().p2(); // 'F.prototype.p2'

另请查看:

  1. JavaScript.protype是如何工作的
  2. http://www.w3schools.com/jsref/jsref_prototype_math.asp
  3. https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/Function/prototype
分配给String原型的方法可以应用于String的所有实例。分配给String构造函数的方法必须以字符串为参数的静态方法调用。如果方法在原型中,则在原型中this引用字符串实例。

因此:

String.prototype.insertLineNr = function(nr){return (nr||1) + ': ' +this;};
//                                                                  ^instance
String.insertLineNo = function(str,nr){return (nr||1) + ': ' +str;};
var str = 'Some line to be numbered';
//apply to instance
console.log(str.insertLineNr(5);        //=> '5: Some line to be numbered'
//can't apply direct String method to instance 
console.log(str.insertLineNo(str,5));   //=> TypeError
//Run String method 
console.log(String.insertLineNo(str,5); //=> '5: Some line to be numbered'

如果方法名称相等,则可以两全其美:

function insrtNr(str,nr){ return (nr||1) + ': ' + str || this;};
String.insertLineNr = insrtNr;
String.prototype.insertLineNr = insrtNr;