1.constructor的字面意思就是構造。它是對象的一個屬性,它對應的值是該對象的「構造者」函數
1 //1、構造函數實例化的對象的constructor 2 function Cmf(n,m){ 3 this.n=n; 4 this.m=m; 5 this.mn=function(){ 6 return this.n+'|'+this.m 7 } 8 } 9 var cmf=new Cmf('c',"q") 10 console.log(cmf.mn()) // c|q 11 console.log(cmf.constructor) // Cmf(n, m) 12 //這裏能夠看出Cmf()實例化的cmf()對象,這個對象的constructor是它的固有屬性。 13 14 //2、基本數據類型的constructor 15 var yi=154 16 console.log(yi.constructor)// Number() 17 var li="qdz" 18 console.log(li.constructor)// String()
2.1原型的constructorthis
1 function Cmf(n,m){ 2 this.n=n; 3 this.m=m; 4 this.mn=function(){ 5 return this.n+'|'+this.m 6 } 7 } 8 9 Cmf.prototype.jn=function(){ 10 return this.m+"!"+this.n 11 } 12 var cmf=new Cmf('c',"q") 13 console.log(cmf.jn()) //q!c 14 console.log(Cmf.prototype) // Cmf { jn=function()} 15 console.log(typeof Cmf.prototype) // object 16 console.log(Cmf.prototype.constructor) // Cmf(n, m) 17 //上面看出構造函數原型的constructor指向了該構造函數。怎麼理解呢,構造函數的原型是個Obj,這個Obj是由什麼構成的呢?是它的構造者 構造函數。
2.2 基本數據類型的constructorspa
String.prototype.cf=function(n){ //給String.prototype這個obj添加方法cf,字符串乘法 return new Array(n+1).join(this) } var d="d" console.log(d.cf(5)) //ddddd console.log(String.prototype) // String { cf=function()} console.log(String.prototype.constructor) // String() //相似於構造函數