我们创建构造函数的时候,原型对象上会有一个constructor属性,它是原型对象所独有的
function Person(name,age){
this.name = name;
this.age = age;
}
var p = new Person("cheng",20);
console.log(p.constructor==Person)
var arr = [1,2,3];
console.log(arr.constructor == Array)
给构造函数添加方法
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("cheng",20);
console.log(p.constructor==Person)//true
function Person(name,age){
this.name = name;
this.age = age;
}
/* 以字面量(对象)的形式给原型对象添加属性 */
Person.prototype = {
sayName:function(){
console.log(this.name)
},
sayAge(){
console.log(this.age)
}
}
/* 问题:就是我们以直接量(对象)形式,给原型对象添加属性的时候,它的
constructor会指向Object
*/
var p = new Person("cheng",20);
console.log(p.constructor)//Object
console.log(p.constructor==Person)//false
console.log(p instanceof Person)//true
//解决办法
function Person(name,age){
this.name = name;
this.age = age;
}
/* 问题:就是我们以直接量(对象)形式,给原型对象添加属性的时候,它的
constructor会指向Object
需要:重置constructor
*/
Person.prototype = {
constructor:Person,
sayName:function(){
console.log(this.name)
},
sayAge(){
console.log(this.age)
}
}
var p = new Person("cheng",20);