__ proto __ 和 prototype的区别图解
Introduce
上一章已经大概讲过大致的区别。这里在强调一次
- __ proto __ 指向构造该对象的构造函数的原型
- prototype是函数特有的,是一个指针,指向包含所有同样继承自这个原型的函数的原型。还是很绕。。哈哈哈哈,语文不好的我。
然后在上一章介绍的那个网站找到了一些相关图片。我这里就分享一下,并且以实例讲解一下。(纯属我的个人见解,如果有问题,请大家见谅)
Pics&&Code
// a constructor function
function Foo(y) {
// which may create objects
// by specified pattern: they have after
// creation own "y" property
this.y = y;
}
// also "Foo.prototype" stores reference
// to the prototype of newly created objects,
// so we may use it to define shared/inherited
// properties or methods, so the same as in
// previous example we have:
// inherited property "x"
Foo.prototype.x = 10;
// and inherited method "calculate"
Foo.prototype.calculate = function (z) {
return this.x + this.y + z;
};
// now create our "b" and "c"
// objects using "pattern" Foo
var b = new Foo(20);
var c = new Foo(30);
// call the inherited method
b.calculate(30); // 60
c.calculate(40); // 80
// let's show that we reference
// properties we expect
console.log(
b.__proto__ === Foo.prototype, // true
c.__proto__ === Foo.prototype, // true
// also "Foo.prototype" automatically creates
// a special property "constructor", which is a
// reference to the constructor function itself;
// instances "b" and "c" may found it via
// delegation and use to check their constructor
b.constructor === Foo, // true
c.constructor === Foo, // true
Foo.prototype.constructor === Foo, // true
b.calculate === b.__proto__.calculate, // true
b.__proto__.calculate === Foo.prototype.calculate // true
);
!
Analysis
- b和c都是通过Foo,new出来的新的对象,首先它不是函数,所以没有prototype,只有隐式原型__ proto __ ,很容易想通,他们的构造函数是Foo,(因为是Foo,new出来的),所以根据我们上面重复了很多的话,__ proto __ 指向构造该对象的构造函数的原型, 构造函数是Foo,那__ proto __自然就是Foo.prototype 。Foo是个函数。具有prototype
- Foo是一个函数,他自然就有prototype和__ proto __ ,作为函数,他的prototype指向Foo.prototype,__ proto __ 指向构造该函数的原型,构造该函数的自然是function(特殊对象,或者叫做头等对象),,那么__ proto __就是function.prototype
- Foo.prototype是对象,他是没有prototype的,只有__ proto __ ,构造该对象的是object,那么 __ proto __ 自然指向object.prototype,function的 __ proto __ 同理。
- object是在原型链顶部的,他的原型只有null。
review
- 在前端的js里,万物都是对象,对象都有proto这个属性,指向构造该对象的构造函数的原型
- 只有函数才有prototype这个属性,这个属性是一个指针,指向包含所有同样继承自这个原型的函数的原型
writer&contact
{
"name":"Jontyy" ,
"email": " jontyy@163.com"
}