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