标签:
构造函甚至不必返回这个新创建的对象,构造函数会自动创建对象,然后将构造函数当作为这个对象的方法来调用一次,最后返回这个新对象。
任何javascript函数都可以用作构造函数,并且调用构造函数是需要用到一个prototype属性的。因此,每个javascript函数(除了ecmascript 5中的Function.bind方法返回的函数之外)都自动拥有一个prototype属性。这个属性的值是一个对象。这个对象包含唯一一个不可枚举属性constructor。constructor属性的值是一个函数对象。
function f(){}; var p=f.prototype; var c=p.constructor; console.log(c);//function f(){} console.log(p);//f {} console.log(c===f);//true
对任意函数F.prototype.constructor==F;
可以看到构造函数的原型中存在预先定义好的constructor属性,这意味这对象通常继承的constructor均指代它们的构造函数,由于构造函数是类的公共标识,因此这个constructor属性为对象提供哦了类
var o=new F();
o.constructor===F;//true
range类使用它自身的一个新对象重写了预定义的rang.prototype对象,这个新定义的原型对象不含有constructor属性。因此range类的实例也不含有constructor属性,我们可以通过补救来修正这个问题,显示的给原型添加一个构造函数:
function Range(){ this.x=1; this.y=2; }; Range.prototype={ constructor:Range }; var p=new Range(); console.log(p.constructor);
另一种常见的解决方法是使用预定义的原型对象,预定义的原型对象包含construtor属性,然后依次给原型对象添加方法
类的扩充
String.prototype.trim=String.prototype.trim||function(){ if(!this)return this; return this.replace(/^\s+|\s+$/g,""); }; console.log(" sdf ".trim());//sdf Function.prototype.getName=function(){ return this.Name|| this.toString().match(/function\s*([^()]*)\(/)[1]; }; function test(){ } console.log(test.getName());//test
标签:
原文地址:http://www.cnblogs.com/yhf286/p/5064718.html