JS面向对象,原型

原型对象

 

function person1(){

}
person1.prototype.name = 'miky';
person1.prototype.age= '18';
person1.prototype.sayName = function(){
console.log(this.name);
}
var p1 = new person1();
p1.sayName();

function person2(){

}
person2.prototype = {
name: 'miky',
age: '18',
sayName: function(){
console.log(this.name);
}
}

var p2 = new person2();
p2.sayName();
console.log(p2 instanceof Object);
console.log(p2 instanceof person2);
console.log(p1.constructor == person1);
console.log(p2.constructor == person2);
console.log(p2.constructor == Object);
 
 
可以在prototype 对象中将constructor 属性重新设置  constructor : person   但是这样操作会导致它的[[Enumerable]] 特性设置为true。默认情况下,原生的constructor属性是不可枚举的,可以用Objece.defineProperty() 方法设回来。
 
在原型中查找值的过程是一次搜索,对原型对象所做的修改能立即从实例中反应出来
 
 
高程3中  174页说明实例与原型不过是一个指针,而非副本。。这就关系到   值复制和指针复制的问题,好好研究下。(C语言)
 
 
重写原型的问题
 
function person2(){

}
var friend = new person2();
// person2.prototype.sayName = function(){
// console.log('hi2');
// }
// friend.sayName();
person2.prototype = {
sayName: function(){
console.log('hi2重写原型对象后');
 
}
}
friend.sayName();
 
不注释的话,后面的friend.sayName()  返回true;
注释的话,后面的friend.sayName()  返回false; 
  
posted @ 2019-04-14 06:14  涂涂前端  阅读(202)  评论(0编辑  收藏  举报