Home > Web Front-end > JS Tutorial > body text

Comprehensive analysis of prototypes in JavaScript

亚连
Release: 2018-05-21 14:53:47
Original
1406 people have browsed it

This article mainly introduces the complete analysis of prototype prototype in JavaScript. Prototype is an important support for the "everything is an object" argument in the js world. It explains the __proto__ attribute and prototype chain and other dry information. Friends who need it can refer to it

To understand prototype in JS, you must first understand the following concepts
1. Everything in JS is an object

2. Everything in JS is derived from Object Comes from, that is, the end point of the prototype chain of all things points to Object.prototype

  // ["constructor", "toString", "toLocaleString", "valueOf", "hasOwnProperty", "isPrototypeOf", 
   // "propertyIsEnumerable", "__defineGetter__", "__lookupGetter__", "__defineSetter__",
   // "__lookupSetter__"]
   console.log(Object.getOwnPropertyNames(Object.prototype));
Copy after login

3. The subtle relationship between constructors and instances (objects) in JS
The constructor agrees on its instance by defining prototype Specifications, and then use new to construct instances, their role is to produce objects.
And the constructor (method) itself is an instance of the method (Function), so its __proto__ (prototype chain) can also be found

Object / function F() {} This is the constructor, one is provided by JS native API, and the other is customized
new Object() / new F() This is what it looks like Example
An instance can "only" check __proto__ to know what prototype it is based on,
but "cannot" redefine the prototype of the instance to create an instance of the instance.

Practice brings true knowledge, only by observing/thinking yourself can you truly understand:

  // 先来看看构造函数到底是什么
  // function Empty() {}  function Empty() {}
  console.log(Function.prototype, Function.__proto__);
  // Object {}          function Empty() {}
  console.log(Object.prototype, Object.__proto__);
  function F() {}
  // F {}              function Empty() {}
  console.log(F.prototype, F.__proto__);
Copy after login

You may be dizzy, let’s break it down.

prototype The format of prototype output is: constructor name prototype
First, let’s take a look at what Object.prototype outputs?
Object {} -> The previous Object is a constructor The name of the function, the last one represents the prototype, here is a {}, that is, an instance of an Object object (empty object)
Then we will understand what F {} means, F is the name of the constructor, and the prototype is also An empty object

  // 再来看看由构造函数构造出来的实例
  var o = new Object(); // var o = {};
  // undefined       Object {}
  console.log(o.prototype, o.__proto__);
  function F() {}
  var i = new F();
  // undefined       F {}
  console.log(i.prototype, i.__proto__);
Copy after login

Let’s go a little deeper and define the prototype of F to see what happens?

  function F() {}
  F.prototype.a = function() {};
  var i = new F();
  // undefined       F {a: function}
  console.log(i.prototype, i.__proto__);
Copy after login

In this way we can clearly see that i is constructed from F, The prototype is {a: function}, which means that the original empty object prototype has a new a method

Let’s change the situation again, what will happen if we completely cover the prototype of F?

function F() {}
  F.prototype = {
    a: function() {}
  };
  var i = new F();
  // undefined       Object {a: function}
  console.log(i.prototype, i.__proto__);
Copy after login

Why~ Why does it show that i is constructed from Object? No!
Because we completely overwrite the prototype of F, which actually means specifying the prototype as object {a: function}, but this will cause the original The constructor information is lost and becomes the constructor specified by the object {a: function}.
So what is the constructor of the object {a: function}?
Because the object {a: function} is actually relative to

var o = {a: function() {}} // new了一个Object
Copy after login

Then of course the constructor of o is Object

Let’s correct this mistake

  function F() {}
  F.prototype = {
    a: function() {}
  }
  // 重新指定正确的构造函数
  F.prototype.constructor = F;
  var i = new F();
  // undefined       F {a: function, constructor: function}
  console.log(i.prototype, i.__proto__);
Copy after login

Now we can get the correct prototype information again~

Prototype chain

Then let’s take a look at what the prototype chain is?
Simply speaking, it is the same as the inheritance relationship (chain) in OOP. You go up layer by layer. , until the final Object.prototype

2016510172352211.jpg (560×248)

## The most important thing is to figure out which things in JS are (instance) objects. This is simple. Everything in JS is Object!

Another thing to understand is that any object has a prototype!

Then let’s prove it:


  Object // 这是一个函数, 函数是 Function 的实例对象, 那么就是由 Function 构造出来的
  Object.__proto__ == Function.prototype // 那么Object的原型, true
  // 这个是一个普通对象了, 因此属于 Object 的实例
  Function.prototype.__proto__ == Object.prototype // true
  // 这已经是原型链的最顶层了, 因此最终的指向 null
  Object.prototype.__proto__ == null // true

  Function // 这也是一个函数, 没错吧!
  Function.__proto__ == Function.prototype // true
  
  function A() {} // 这是一个自定义的函数, 终归还是一个函数, 没错吧! 
  A.__proto__ == Function.prototype // 任何函数都是 Function 的实例, 因此A的原型是?
  var a = new A()
  a.__proto__ == A.prototype // 实例a是由A构造函数构造出来的, 因此a的原型是由A的prototype属性定义的
  A.prototype.__proto__ == Object.prototype // 普通对象都是 Object 的示例
Copy after login

Prototype and __proto__Each object contains a __proto__, pointing to the "prototype" of this object. A similar thing is that each function contains a prototype. What does this prototype object do?

Let’s take a look at the following code, using the constructor to create an object (the above is to create an object in the form of a literal).

function Foo(){};
var foo = new Foo();
console.log(foo.__proto__);
Copy after login

Just think about it, what does the __proto__ of this foo object point to?

2016510172448163.png (163×68)

An object containing a constructor property? It doesn’t matter if you don’t understand it well. Just print out the prototype attribute of function Foo and compare it.

function Foo(){};
var foo = new Foo();
console.log(foo.__proto__);
console.log(Foo.prototype);
console.log(foo.__proto__ === Foo.prototype);
Copy after login

2016510172512274.png (183×69)

It turns out that the __proto__ of the new object foo only points to the prototype of the function Foo.

foo.__proto__ --> Foo.prototype
Copy after login
Copy after login

What’s the point of designing JS like this? Recall what was said above, in the world of JS, objects are not created based on classes (molds), but derived from prototypes (another object).

When we perform the new operation to create a new object, we will not go into the specific implementation of the new operation, but one thing we are sure of is that the __proto__ of the new object points to a prototype object.

Just this code

function Foo(){};
var foo = new Foo();
Copy after login

foo.__proto__到底要指向谁了?你怎么不能指向Foo这个函数本身吧,虽然函数也是对象,这个有机会会详细讲。但如何foo.__proto__指向Foo固然不合适,因为Foo是一个函数,有很多逻辑代码,foo作为一个对象,继承逻辑处理没有任何意义,它要继承的是“原型对象”的属性。

所以,每个函数会自动生成一个prototype对象,由这个函数new出来的对象的__proto__就指向这个函数的prototype。

foo.__proto__ --> Foo.prototype
Copy after login
Copy after login

总结说了这么多,感觉还是没完全说清楚,不如上一张图。我曾经参考过其他网友的图,但总觉得哪里没说清楚,所以我自己画了一张图,如果觉得我的不错,请点个赞!(老子可是费了牛劲才画出来)。

2016510172555695.png (800×600)

咱们就着这张图,记住如下几个事实:

1. 每个对象中都有一个_proto_属性。

JS世界中没有类(模具)的概念,对象是从另一个对象(原型)衍生出来的,所以每个对象中会有一个_proto_属性指向它的原型对象。(参考左上角的那个用字面量形式定义的对象obj,它在内存中开辟了一个空间存放对象自身的属性,同时生成一个_proto_指向它的原型——顶层原型对象。)

2. 每个函数都有一个prototype属性。

“构造函数”为何叫构造函数,因为它要构造对象。那么根据上面第一条事实,构造出来的新对象的_proto_属性指向谁了?总不能指向构造函数自身,虽然它也是个对象,但你不希望新对象继承函数的属性与方法吧。所以,在每个构造函数都会有一个prototype属性,指向一个对象作为这个构造函数构造出来的新对象的原型。

3. 函数也是对象。

每个函数都有一些通用的属性和方法,比如apply()/call()等。但这些通用的方法是如何继承的呢?函数又是怎么创建出来的呢?试想想,一切皆对象,包括函数也是对象,而且是通过构造函数构造出来的对象。那么根据上面第二条事实,每个函数也会有_proto_指向它的构造函数的prototype。而这个构造函数的函数就是Function,JS中的所有函数都是由Function构造出来的。函数的通用属性与方法就存放在Function.prototype这个原型对象上。

上面是我整理给大家的,希望今后会对大家有帮助。

相关文章:

全面分析JavaScript面向对象概念中的Object类型与作用域(附有示例)

在javascript中创建对象的各种模式解析(图文教程)

详细解读JavaScript设计模式开发中的桥接模式(高级篇)

The above is the detailed content of Comprehensive analysis of prototypes in JavaScript. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template