Prototype inheritance in JavaScript Basic Learning Tutorials _ Basics

Source: Internet
Author: User
Tags constructor inheritance hasownproperty

In most programming languages, there are classes and objects, and a class can inherit other classes.
In JavaScript, inheritance is prototype based (prototype-based), which means that there is no class in JavaScript and that an object inherits another object instead. :)

1. Inheritance, the Proto
in JavaScript, when an object rabbit inherits another object animal, this means that there will be a special attribute in the Rabbit object: rabbit.__proto__ = animal;
When the Rabbit object is accessed, if the interpreter cannot find the attribute in rabbit, it looks up in the animal object along the __proto__ chain
Pest's __proto__ properties are accessible only in Chrome and Firefox, please look at a chestnut:

var animal = {Eats:true}
var rabbit = {Jumps:true}

rabbit.__proto__ = animal//Inherit

alert (rabbit.eat s)//True

The Eats property is accessed from the Animal object.
If an attribute has been found in the Rabbit object, then the Proto property is not checked.
Another chestnut, when the subclass also has the Eats property, the parent class will not be accessed.

var animal = {Eats:true}
var feduprabbit = {Eats:false}

feduprabbit.__proto__ = Animal 

alert (feduprabbit. Eats)//False

You can also add a function to the animal, and you can also access it in rabbit.

var animal = {
 eat:function () {
  alert ("I ' m full")
  This.full = True
 }
}


var rabbit = {
 Jump: function () {/* Something/}
}

rabbit.__proto__ = Animal 

(1) rabbit.eat ():
The Rabbit.eat () function is executed in the following two steps:
First, the interpreter finds no eat function in the rabbit.eat,rabbit, then it looks up the rabbit.__proto__ and finds it in animal.
function to run with this = rabbit. This value is completely unrelated to the __proto__ property.
Therefore, This.full = True is in rabbit:
Look at what we've found here, an object called the parent class function, but this still points to the object itself, which is inheritance.
The object referenced by the __proto__ is called a prototype (prototype), and animal is the Rabbit prototype (translator Note: This is rabbit's __proto__ attribute that references animal properties)
(2) Read-time lookup, not when writing
When reading an object, such as This.prop, the interpreter looks up the attribute in its prototype.
When setting a property value, such as This.prop = value, there is no reason to look, this attribute (prop) is added directly to the object (here is this). The delete Obj.prop is similar in that it deletes only the properties of the object itself, and the properties in the prototype remain intact.
(3) About Proto
If you are reading the guide, here we call the __proto__, which is represented in the guide as [[Prototype]]. Both brackets are important because there is another property called prototype.

2. Object.create, object.getprototypeof
__proto__ is a non-standard property that is accessed by Chrome/firefox and remains invisible in other browsers.
All modern browsers except opera (IE > 9) support two standard functions to handle prototyping problems:

Object.ceate (Prop[,props])

Creates an empty object with the given proto:

var animal = {Eats:true}

rabbit = object.create (animal)

alert (rabbit.eats)//True

The above code creates an empty rabbit object, and the prototype is set to animal
Once the Rabbit object is created, we can add attributes to it:

var animal = {Eats:true}

rabbit = object.create (animal)
Rabbit.jumps = True

The second parameter of the Object.creat function, props, is optional, allowing properties to be set like new objects. Here is omitted, because of the inheritance of our relationship.
(1) object.getprototypeof (obj)
Returns the value of the obj.__proto__. This function is standard and can be used in browsers that do not have direct access to the __proto__ property.

var animal = {
 eats:true
}

rabbit = object.create (animal)

alert (object.getprototypeof (rabbit) = = Animal)//True

Modern browsers allow __proto__ property values to be read, but cannot be set.

3. The prototype
There are some good cross-browser ways to set the __proto__ property, which will use constructor functions (constructor functions). Remember! Any function that creates an object is through the new keyword.
A chestnut:

function Rabbit (name) {
 this.name = name
}

var Rabbit = new Rabbit (' John ')

alert (rabbit.name)//John

The new operation sets the properties of the stereotype to the __proto__ property of the Rabbit object.
Let's look at how it works, for example, the new Rabbit object, and Rabbit is inherited animal.

var animal = {Eats:true}

function Rabbit (name) {
 this.name = name
}

rabbit.prototype = Animal

var rabbit = new Rabbit (' John ')

alert (rabbit.eats)/true, because rabbit.__proto__ = = Animal

Rabbit.prototype = animal literal means: set __proto__ = Animal for all objects created by new Rabbit

4. Cross-browser object.create (proto)
the Object.create (prop) function is powerful because it allows direct inheritance from a given object. It can be modeled by the following code:

function inherit (proto) {
 function F () {}
 F.prototype = Proto return
 new F
}

Inherit (animal) is exactly equivalent to object.create (animal), returns an empty object, and object.__proto__ = animal.
A chestnut:

var animal = {Eats:true}

var rabbit = inherit (animal)

alert (rabbit.eats)/True
alert (rabbit.hasownprope Rty (' eats '))//False, from prototype

Take a look at the principle of what it is:

function inherit (proto) {
 function F () {}   //(1)
 F.prototype = Proto//(2) Return to
 new F ()   //(3)
}

(1) A new function is created, and the function does not set any properties to this, and the ' new F ' creates an empty object.
(2) ' F.prototype ' is set to Proto
(3) ' new ' F creates an empty object, the object's ' __proto__ = F.prototype '
(4) bingo! We've got an empty object that inherits ' Proto '
This function is widely used in various libraries and frameworks.
Your function accepts an object with options.

/* Options contains menu settings:width, height etc *
/function menu (options) {
 //...
}
You want to set certain options
function Menu {
 options.width = Options.width | |//SET DEFAULT value
 //...
}

。。。 However, changing the parameter values may result in some erroneous results because the options may be used in external code. One solution is to clone the Options object, copy all the attributes into a new object, modify it in the new object,
How to use inheritance to solve this problem? P.S. Options can add settings, but cannot be deleted.
Solution
You can inherit the options and modify or add new attributes in its subclasses.

function inherit (proto) {
 function F () {}
 F.prototype = Proto return
 new F
}

function Menu ( Options) {
 var opts = inherit (options)
 opts.width = Opts.width | |


All operations are valid only in child objects, and when the menu method finishes, the external code can still use the option object that has not been modified. The delete operation is very important here, and if width is an attribute in a prototype, delete Opts.width will not have any effect

5. hasOwnProperty
all objects have hasownproperty functions that can be used to detect whether an attribute is an object or a prototype.
A chestnut:

function Rabbit (name) {
 this.name = name
}

rabbit.prototype = {eats:true}

var Rabbit = new Rabbit (' John ')

alert (rabbit.hasownproperty (' eats '))//False, in prototype

alert (rabbit.hasownproperty (' name '))//True, In Object

6. Looping With/without inherited properties
for.. The in loop outputs all the attributes of an object, including its own and its prototypes.

function Rabbit (name) {
 this.name = name
}

rabbit.prototype = {eats:true}

var Rabbit = new Rabbit (' John ') for

(Var p in rabbit) {
 alert (p + "=" + rabbit[p])//Outputs both "name" and "Eats"
}

With hasOwnProperty, you can filter the properties that belong to the object itself:

function Rabbit (name) {
 this.name = name
}

rabbit.prototype = {eats:true}

var Rabbit = new Rabbit (' John ') for

(Var P-Rabbit) {
 if (!rabbit.hasownproperty (p)) Continue//filter out "eats"
 alert (p + "=" + Rabb IT[P])//Outputs only "name"
}

7. Summary
JavaScript is implemented through a special attribute proto.
When accessing an object's properties, if the interpreter cannot find it in the object, it goes to the object's prototype to look for the function attribute, this points to the object, not its prototype.
Assignment Obj.prop = value, deleting delete obj.prop
Management Proto:
Chrome and Firefox can directly access the object's __proto__ properties, and most modern browsers support read-only access with object.getprototypeof (obj).
Object.create (proto) can generate an empty child object with a given proto, or achieve the same functionality through the following code:

function inherit (proto) {
   function F () {}   
   F.prototype = Proto return
   new F ()  
  }

Other methods:
For.. The in loop outputs all the attributes of an object (both own and prototype) and the prototype chain of the object.
If a property prop belongs to object obj then Obj.hasownproperty (prop) returns true, otherwise it returns false.

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.