4.1给原型添加属性
创建构造函数的时候,原型对象上会有一个constructor属性,它是原型对象所独有的,它指回构造函数本身
function Person(name,age){
this.name=name;
this.age=age;
}
Person.prototype.sayName=function(){
console.log(this.name)
}
Person.prototype.sayAge=function(){
console.log(this.age)
}
var p=new Person("meng",21)
console.log(p)
console.log(p.constructor==Person)//true
var arr=[1,2,3];
console.log(arr.constructor==Array)//true
4.2给原型添加属性
以直接量形式(对象),给原型对象添加属性的时候,他的contructor会指向object
function Person(name,age){
this.name=name;
this.age=age;
}
Person.prototype={
sayName:function(){
console.log(this.name)
},
sayAge(){
console.log(this.age)
}
}
var p=new Person("meng",21);
console.log(p)
console.log(p.constructor);
console.log(p.constructor==Person)//false
console.log(p instanceof Person)//true
方法:重置constructor constructor=Person
function Person(name,age){
this.name=name;
this.age=age;
}
Person.prototype={
constructor:Person,//重置constructor
sayName:function(){
console.log(this.name)
},
sayAge(){
console.log(this.age)
}
}
var p=new Person("meng",21);
console.log(p.constructor);
console.log(p.constructor==Person)//true
4.3 公有属性和私有属性
公有:在一般的原型对象上
私有:通过this关键字添加 (sayName sayAge)
hasOwnProperty判断属性是公有还是私有
function Person(name,age){
this.name=name;
this.age=age;
}
Person.prototype={
constructor:Person,//重置constructor
sayName:function(){
console.log(this.name)
},
sayAge(){
console.log(this.age)
}
}
var p=new Person("meng",21);
console.log(p.hasOwnProperty("name"));//true 私有
console.log(p.hasOwnProperty("sayAge"));//false 公有
console.log(p.hasOwnProperty("sayName"));//false 公有