Discuss / JavaScript / 关于proto和__proto__的区别

关于proto和__proto__的区别

Topic source

水蔓姐姐

#1 Created at ... [Delete] [Delete and Lock User]

感觉有点绕,敲了一下有一点小小的发现。

var Student = {
    name:'Student',
    age:3,
    run: function(){
        console.log(this.name + 'is running');
    }
};

a = new Object(Student);
b = Object.create(Student);

// 重点来了
a.proto === Student.prototype; //true
b.proto === Student.prototype; //true

b.__proto__ === Student; //true
a.__proto__ === Student; //false
a.__proto__ === Student.__proto__; //true

上面的a是用new Object生成,感觉就是Student本身(或者类似指针?)。因为把在console改变a的属性也会把Student和属性改了。

也因为a就是Students对象,而b对象是从Studnents对象“继承”过来的。也因此,a.__proto__b.__proto__完全不同。而实际上Studnent(也就是a).proto和b.proto都是从Students.prototype构建的,所以这是一样的。

但是从Object生成Student时和从Student生成b不一样,因为

b.__proto__ === Student; //true
Student.__proto__ === Object; // false
Student.__proto__ === Object.prototype; // true

不知道是不是这么理解:

  • Object.prototype 生成Student.prototype,它同时生成了一个Student对象 Student.protoytype
  • Student.prototype 可以生成xiaoming之类的对象(类似继承)

  • xiaoming.__proto__是原型(Student.prototype)的对象Student

  • xiaoming.proto是原型本身Student.prototype

  • new Object(Student)生成的对象是Student本身(或者类似指针的东西?),prototype是Student.prototype,__proto__是Object.prototype

  • Object.create(Student)方法生成的对象xiaoming是新的对象,但prototype还是prototype是Student.prototype,但__proto__是Student对象

或许这就是子类父类的意思把。proto是父类,proto表示是自己的类型。 从动物类派生出狗类和鸟类的。 狗和鸟都是动物。但是显然狗类不是鸟类。

http://www.cnblogs.com/wangfupeng1988/p/3977924.html

这有个原型链的教程,应该有点用

a.proto === Student.prototype; //true
b.proto === Student.prototype; //true

这两行代码为 true,是因为 === 俩边都是 undefined,对象没有 prototype 属性 和 proto 属性,你说的 proto 应该是指 __proto__ 这一内部属性。

Junes_99994

#5 Created at ... [Delete] [Delete and Lock User]

1 ---------

1 a: {name: 'student', age: 3, run: ƒ}

2 a.__proto__: {constructor: ƒ, __defineGetter__: ƒ, __defineSetter__: ƒ, hasOwnProperty: ƒ, __lookupGetter__: ƒ, …}

3 a.constructor: ƒ Object()

2 ---------

1 b: {}

2 b.__proto__: {name: 'student', age: 3, run: ƒ}

3 b.constructor: ƒ Object()

#6 Created at ... [Delete] [Delete and Lock User]

感谢法式芒果绿欧蕾,将的很清楚,彻底理解了原型啥意思,谢谢

Vincent

#7 Created at ... [Delete] [Delete and Lock User]

感谢法式芒果绿欧蕾,博客写得挺好的。


  • 1

Reply