原型对象详解
function Student(){
Student.prototype.name = 'lisi';
Student.prototype.age = 18;
Student.prototype.say = function(){
console.log(Student.prototype.name);
}
}
var student1 = new Student();
var student2 = new Student();
student1.say();
当Student被创建时,就会产生一个prototype属性(指针),指向原型对象,而原型对象中会有一个constructor属性(指针),又指回Student函数。当student1与student2被创建时,他们的prototype属性会指向Student的原型对象,它们的关系就如下图:
原型对象的属性和方法可以被删除修改吗??答案是否定的
function Student(){
Student.prototype.name = 'lisi';
Student.prototype.age = 18;
Student.prototype.say = function(){
console.log(this.name);
}
}
var student1 = new Student();
delete(student1.name)
student1.say();
最后还是会打印lisi。说明并没有删掉name属性
再比如说
var student1 = new Student();
student1.name = 'san';
student1.say();//san
var student2 = new Student();
student2.say();//lisi
student1.name = 'san';相当于在student1中声明了一个name属性,
student1.say()它会现在当前实例中查找name属性,如果找到就访问该属性,没找到就会到原型对象上查找。比如说第二个student2实例
如何判断一个属性是原型对象的属性还是实例中的属性?
hasOwnProperty:
console.log(student1.hasOwnProperty('name')); //true student1的name属性是在实例中定义的
console.log(student2.hasOwnProperty('name')); //fales 原型上定义的
如何判断对象的属性是否存在?
in:
console.log("name" in student1);//true
console.log("name" in student2);//true
无论改属性在原型中还是在实例中都返回true;
function Student(){
Student.prototype.name = 'lisi';
Student.prototype.age = 18;
Student.prototype.say = function(){
console.log(Student.prototype.name);
}
}
var student1 = new Student();
var student2 = new Student();
student1.say();
当Student被创建时,就会产生一个prototype属性(指针),指向原型对象,而原型对象中会有一个constructor属性(指针),又指回Student函数。当student1与student2被创建时,他们的prototype属性会指向Student的原型对象,它们的关系就如下图:
原型对象的属性和方法可以被删除修改吗??答案是否定的
function Student(){
Student.prototype.name = 'lisi';
Student.prototype.age = 18;
Student.prototype.say = function(){
console.log(this.name);
}
}
var student1 = new Student();
delete(student1.name)
student1.say();
最后还是会打印lisi。说明并没有删掉name属性
再比如说
var student1 = new Student();
student1.name = 'san';
student1.say();//san
var student2 = new Student();
student2.say();//lisi
student1.name = 'san';相当于在student1中声明了一个name属性,
student1.say()它会现在当前实例中查找name属性,如果找到就访问该属性,没找到就会到原型对象上查找。比如说第二个student2实例
如何判断一个属性是原型对象的属性还是实例中的属性?
hasOwnProperty:
console.log(student1.hasOwnProperty('name')); //true student1的name属性是在实例中定义的
console.log(student2.hasOwnProperty('name')); //fales 原型上定义的
如何判断对象的属性是否存在?
in:
console.log("name" in student1);//true
console.log("name" in student2);//true
无论改属性在原型中还是在实例中都返回true;