JavaScript之构造函数初了解

调用时函数名加上()代表调用这个函数,不加()表示代表这个函数的内容。

可以自定义自己的构造函数,只需要编写一个为this添加属性的函数就可以。直接用例子说明:

var width;  

var height;

function Rectangle(w,h){

this.width = w;//this关键字必须有

this.height = h; }//this关键字必须有

var rect = new Rectangle(3,2);//创建实例

alert(rect.width);//调用

原型对象是放置方法和其他不变属性的理想地方。所有的函数都有一个prototype属性,当这个函数被定义的时候,prototype属性自动创建和初始化。prototype属性的初始化值是一个对象,这个对象只带有一个属性。这个属性名为constructor,他指回到和原型相关联的那个构造函数,这就是每个对象都有一个constructor属性的原因。添加给这个原型对象的任何属性,都会成为被构造函数所初始化的对象的属性。例子:

 function Rectangle(w,h){

 this.width = w;

this.height = h; 

}

Rectangle.prototype.area = function(){return this.width * this.height;} 

我们可以使用Object.hasOwnProperty()来区分继承的属性和常规的属性。例子:

var r = new Rectangle(2,3);

r. hasOwnProperty("width");//return true widths是继承的属性

r. hasOwnProperty("area");//return false

 
 
原文地址:https://www.cnblogs.com/lee0oo0/p/2534228.html