A Plain 中文版 Guide to JavaScript prototypes

Source: Internet
Author: User

When I first started learning about JavaScript object model My reaction is of horror and disbelief. I was totally puzzled by its prototype nature as it is my first encounter with a prototype based language. I didn ' t help that JavaScript have a unique take on prototypes as it adds the concept of function constructors. I bet that many of you has had similar experience.

But as I used JavaScript more I didn ' t just learn to understand its object model but also started love parts of it. Thanks to JavaScript I has find out the elegance and flexibility of prototypes languages. I am now quite fond of prototype languages because they has a simpler and more flexible object model than class based LAN Guages.

Prototypes in Javascript

Most guides/tutorials start explaining JavaScript objects by going directly to 'constructor functions', I think This was a mistake, as they introduce a fairly complex concept early on making Javascript look difficult and confusing fro M the start. Let's leave this for later. First let's start with the basics of prototypes.

Prototype chains (aka Prototype Inheritance)

Every object in Javascript has a prototype. When a messages reaches a object, JavaScript would attempt to find a property in this object first, if it cannot find it t Hen the message is sent to the object's prototype and so on. This works just like single parent inheritance in a class based language.

Prototype inheritance chains can go as long as you want. But the general it's not a good idea to make long chains as your code can get difficult to understand and maintain.

The __proto__ object

To understand prototype chains in JavaScript there was nothing as the "the __proto__property." Unfortunately __proto__ is not a part of the that standard interface of JavaScript, not at least until ES6. So you shouldn ' t use it in production code. But anyway it makes explaining prototypes easy.

//Let's create an alien objectvarAlien ={kind:' Alien '}//and a Person objectvarperson ={kind:' Person '}//And an object called ' Zack 'varZack = {};//assign Alien as the prototype of Zackzack.__proto__ =Alien//Zack is now linked to Alien//it ' inherits ' the properties of alienConsole.log (Zack.kind);//= ' Alien '//assign Person as the prototype of Zackzack.__proto__ = Person//And now Zack was linked to personConsole.log (Zack.kind);//= ' person '

As you can see the __proto__ property was very straightforward to understand and use. Even if we shouldn ' t use __proto__ on Production code, I think that these examples give the best foundation to UN Derstand the JavaScript object model.

You can check the. One object is the prototype of another by doing:

Console.log (Alien.isprototypeof (Zack)) // = True
Prototype Lookups is dynamic

You can add properties to the prototype of a object at any time, the prototype chain lookup would find the new property as Expected.

  {}  var  Zack = {}zack.__proto__  = person  //  Zack doesn ' t respond to kind on this Point  Console.log (Zack.kind); // => undefined  //  Let's add kind to person  person.kind = ' person ' //< /span> Now Zack responds to kind  //  because it finds ' kind ' in person  console.log (zack.kind); // => ' person '  
new/updated Properties is assigned to the object, not to the prototype

What happens if do update a property, already exists in the prototype? Let's see:

var person = {  ' person '}var zack == = ' Zack '//  = ' Zack '//  Zack now have a ' kind 'property//= = Person '// person have not being modified

Note that the property ' kind ' now exists in both person and Zack.

Object.create

As explained before __proto__ is not a well supported it's the assigning prototypes to objects. So the next simplest-on is using object.create (). This was available in ES5, but the old Browsers/engines can was shimmed using this es5-shim.

var person = {  "person"}//  creates a new object which prototype is PERSONvar zack = object.create (person);   // = ' person '

You can pass a object to Object.create-add specific properties for the new object

var zack = Object.create (person, {age: {value:  +//  = ' + ')

Yes, the object need to pass was a bit convoluted, but that's the it is. See the docs here.

Object.getprototype

You can get the prototype of an object using object.getprototypeof

var zack =// = = Person

There is no such thing as Object.setprototype.

Constructor Functions

Constructor Functions is the most used the "in JavaScript" to construct prototype chains. The popularity of constructor functions comes from the fact, this is the only original-to constructing Types. It is also a important consideration the fact that many engines was highly optimized for constructor functions.

Unfortunately they can get confusing, they is in my opinion one of the main reasons why new comers find JavaScript Puzzli Ng, but they is a big part of the language and we need to understand them well.

Functions as constructors

In JavaScript, create an instance of a function like this:

function Foo () {} var New Foo (); // Foo is now an instance of Foo instanceof // = True

In essence functions when used with the keyword new behave like factories, meaning that they create new objects . The new object they create is linked to the function by its prototype, and more on this later. So-in JavaScript we call this a instance of the function.

' This ' is assigned implicitly

When we use 'new', JavaScript injects a implicit reference to the new object being created in the form of the ' C1>this' keyword. It also returns this reference implicitly at the end of the function.

When we do this:

function Foo () {  this. Kind = ' foo '}varnew//= = ' Foo '

Behind The scenes it is like doing something like this:

 function   Foo () { var  this  = {}; //      this . __proto__ = Foo.prototype;   ' foo '  return  this  ;}  

But keep on mind, the implicit 'this ' was only assigned to a new object when using 'new'. If you forget 'new' keyword then 'this ' 'll be is the global object. Of course forgetting new is a cause of multiple bugs, so don ' t forget new.

One convention that I-like was capitalizing the first letter of a function when it was intented to be used as a function con Structor, so-straightaway to you is missing the new keyword.

The ' function prototype '

Every function in JavaScript have a special property called 'prototype'.

function Foo () {}foo.prototype

As confusing as it may sound, this 'prototype' was not a real prototype (__proto__) of the fun Ction.

// = False

This is course generates a lot of confusion as people with the term 'prototype' to refer to different things. I think that a good clarification are to always refer to the special 'prototype' property of functions as ' the Function prototype', never just 'prototype'.

The 'prototype' property points to the object that would be a asigned as the prototype of instances created with tha t function when using 'new'. Confusing? This is easier to explain with an example:

functionPerson (name) { This. Name =name;}//The function person had a prototype property//we can add properties to this function prototypePerson.prototype.kind =' person '//When we create a new object using newvarZack =NewPerson (' Zack ');//The prototype of the new object points to Person.prototypezack.__proto__ = = Person.prototype//= True//In the new object we had access to properties defined in Person.prototypeZack.kind//= Person

That's mostly everything there is-know about the JavaScript object model. Understanding how __proto__ and Function.prototype is related would give you countless hours of joy and Satisfaction, or maybe not.

Mistakes, confusing? Let me know.

A Plain 中文版 Guide to JavaScript prototypes

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.