原型对象详解

原型对象详解
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;
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值