prototype 和 proto

prototype:

prototype 函数才有prototype 是对象类型 typeof Person.prototype --> 'object' Function
创建一个Person类
function Person(){
this.age = 22;
this.name = 'tony';
}

Person.prototype.headCount = 1;
  将对象共同拥有的属性写在prototype里面,节省内存。
    var p = new Person()//p1.constructor(p1的构造器) --> function Person()
console.log(p.headCount)// -->1
Person.prototype.headCount = 2;
console.log(p.headCount)// -->2
//js的类是伪类,本质上p1和Person没有关系,p1和Person.prototype才有关系
Person.name = 1234;
console.log(p.name)// --> tony

// __proto__(谷歌和火狐有,ie没有) p1和Person.prototype的联系 函数隐藏的属性
console.log(p.__proto__);// --> Object {headCount: 1} (Object是一个对象)
// p运行时和Person没有关系,p实例化出来之后,里面的变量有age、name 还有一个隐形的变量__proto__
// 当访问p.headCount时,p本身没有headCount这个变量,p就会通过__proto__去Person.prototype里面找
console.log(p.__proto__.headCount)// --> 2
//
Person.prototype.headCount = 3;
console.log(p.headCount)// -->3
//给Person.prototype重新赋值
Person.prototype = {call:'hello '}
console.log(p.call)// -->undefined
console.log(p.headCount)// -->3
console.log(Person.prototype) // --> Object {call: "hello "}
var p1 = new Person()
console.log(p1.call)// --> hello
//结论:Person.prototype的改变对p没有影响,因为p.__proto__指向的是Person.prototype改变之前的对象,
//Person.prototype改变之后,之前的对象依然存在没有消失,所以p.call是undefined,p.headCount是3
//Person.prototype改变之后,只对改变以后新创建的对象有影响。

//查找属性的过程
console.log(p1.call)// --> hello
p1.call = '你好!';
console.log(p1.call)// --> 你好!
console.log(Person.prototype.call)// --> hello
//结论:p1.call = '你好!',给p1添加了call这个,p1自己就有了call这个属性,访问p1.call时,在p1里面
// 就找到了call,就不会再去Person.prototype里面去找


// 总结 prototype 和 proto的区别
// 1、prototype属性是公有的,只要是函数都有这个属性,都可以用。__proto__是私有的,是对象才有的,指向
// 构造函数的原型,用于研究,只有谷歌和火狐才能用

转载于:https://www.cnblogs.com/wvvv/p/5638187.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值