(1)构造函数的简单介绍
构造函数的特点有:
a.构造函数的首字母大写;
b.内部使用this,指向生成的对象的实例
c.使用new 创建实例
构造函数的缺点:
所有对象都继承构造器里面的方法和属性,但这些方法和属性都是独有的,不是共享的。
下面举个例子说明:
function Persion() {
this.name='陈志豪';
this.say=function () {
return "hi";
}
}
var man=new Persion();
var woman=new Persion();
woman.name="Kate";
console.log(man.name);//陈志豪
console.log(woman.name);//Kate
console.log(man.name);//陈志豪
console.log(man.say()===woman.say())//true
console.log(man.say===woman.say)//false
console.log(man.say())//这是方法返回的字符串
console.log(man.say)//这是方法
从上面可以看到,js 生成的对象,属性和方法都是不共享的
(2)prototype的作用
每一个构造函数都有一个prototype属性,这个属性是构造函数生成的对象实例的原型对象,即基础父类。这个prototype对于构造函数来说,是一个属性,对于生成的对象来说,是一个原型对象。prototype的作用是让构造函数生成的对象共享方法和属性,弥补构造函数的缺点。例子说明:
function Persion() {
this.name='陈志豪';
this.say=function () {
return "hi";
}
}
var man=new Persion();
var woman=new Persion();
woman.name="Kate";
Persion.prototype.ask=function () {
return 'who are you ?'
}
Persion.prototype.status='good';
console.log(Object.getOwnPropertyNames(Persion))//["length", "name", "arguments", "caller", "prototype"]
console.log(Object.getOwnPropertyNames(Persion.prototype))//["constructor", "ask", "status"]
console.log(Persion.prototype)//Object {status: "good"}
console.log(Persion.prototype.prototype)//undefined
console.log(man.prototype===Persion.prototype)//false
console.log(man.prototype)//undefined ,说明prototype是构造函数的属性,不是生成的对象的属性
上面代码有注释,自己看可以发现一些原理。
Object.getOwnPropertyNames(Persion) //看看Persion 有什么属性
Persion.hasOwnPropterty('ask')//Persion是否有一个属性叫'ask',在上例中,会返回false。因为它是Persion.prototype(原型对
象,可以理解为Java父类的对象)的属性,不是Persion的属性的地方
(3)构造器的prototype的constructor属性。
注意我说的是构造器的prototype的constructor属性,不是构造器的constructor属性,有点啰
嗦,但有必要强调一下
function Persion() {
this.name='陈志豪';
}
var girl=new Persion.prototype.constructor()
console.log(Persion.prototype.constructor)//function Persion() {this.name='陈志豪';}
console.log(girl.constructor)//function Persion() {this.name='陈志豪';}
console.log(Persion.constructor)//function Function() { [native code] }
//利用Persion.prototype.constructor或者girl.constructor才能正确的创建对象,
// Persion.constructor不行
(4)instanceof 运算符,判断是否某个构造器生成的对象,返回布尔值。
注意用instanceof 判断是否原型,或者原型的原型 ... ... 的实例对象,也会返回true
function Persion() {
this.name='陈志豪';
}
var girl=new Persion.prototype.constructor()
var boy=new Persion()
console.log(girl instanceof Persion)//true
console.log(boy instanceof Persion)//true
console.log(girl instanceof Object)//true