Basic Learning for prototype inheritance in JavaScript tutorial _ basic knowledge

Source: Internet
Author: User
Tags hasownproperty
This article mainly introduces the basic learning tutorial on prototype inheritance in JavaScript. prototype-based inheritance is the basic method for implementing the inheritance features in Object-Oriented JavaScript, for more information, see classes and objects in most programming languages. One class can inherit other classes.
In JavaScript, inheritance is prototype-based, which means that there is no class in JavaScript. Instead, one object inherits from another object. :)

1. Inheritance, the proto
In JavaScript, when an object rabbit inherits another object animal, this means that the rabbit object will have a special attribute: rabbit. _ proto _ = animal;
When accessing the rabbit object, if the interpreter cannot find the attribute in rabbit, it will search for the attribute in the animal object following the _ proto _ chain.
The _ proto _ attribute in the chestnut can only be accessed in Chrome and FireFox. Please refer to the following example:

var animal = { eats: true }var rabbit = { jumps: true }rabbit.__proto__ = animal // inheritalert(rabbit.eats) // true

The eats attribute is accessed from the animal object.
If the property has been found in the rabbit object, the proto attribute will not be checked.
If the subclass also has the eats attribute, 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 in animal, so 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 looks for rabbit. eat. If there is no eat function in rabbit, it goes up to rabbit. _ proto _ and finds it in animal.
The function runs with this = rabbit. This value has nothing to do with the _ proto _ attribute.
Therefore, this. full = true is in rabbit:
Let's take a look at what we found here. An object calls the parent class function, but this still points to the object itself, which is inheritance.
The object referenced by _ proto _ is called prototype and animal is the prototype of rabbit: the _ proto _ attribute of rabbit references the prototype attribute of animal)
(2) read search, not write
When reading an object, such as this. prop, the interpreter searches for properties in its prototype.
When setting a property value, such as this. prop = value, there is no reason to search for it. this property (prop) will be directly added to this object (this here ). Delete obj. prop is similar. It only deletes the attributes of the object, and the attributes in the prototype remain intact.
(3) about proto
If you are reading the guide, here we call it _ proto __, which is represented as [Prototype] in the Guide. Brackets are important because another attribute is prototype.

2. Object. create, Object. getPrototypeOf
_ Proto _ is a non-standard attribute, which is accessible by Chrome/FireFox and invisible in other browsers.
All modern browsers except Opera (IE> 9) support two standard functions to handle prototype problems:

Object.ceate(prop[,props])

Create 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.
After 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 props of the Object. creat function is optional. It allows you to set attributes like new objects. This is omitted because of the inheritance of our relationship.
(1) Object. getPrototypeOf (obj)
Returns the value of obj. _ proto. This function is standard and can be used in browsers that cannot directly access the _ proto _ attribute.

var animal = { eats: true}rabbit = Object.create(animal)alert( Object.getPrototypeOf(rabbit) === animal ) // true

Modern browsers allow reading the value of _ proto _, but cannot set it.

3. The prototype
There are some good cross-browser ways to set the _ proto _ attribute, which will use constructor functions ). Remember! Any function creates an object using the new keyword.
One chestnut:

function Rabbit(name) { this.name = name}var rabbit = new Rabbit('John')alert(rabbit.name) // John

The new operation sets the prototype property to the _ proto _ attribute of the rabbit object.
Let's take a look at its principles, such as the new Rabbit object, which inherits animal.

var animal = { eats: true }function Rabbit(name) { this.name = name}Rabbit.prototype = animalvar rabbit = new Rabbit('John')alert( rabbit.eats ) // true, because rabbit.__proto__ == animal

Rabbit. prototype = animal literal meaning: 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 simulated by the following code:

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

Inherit (animal) is exactly the same as Object. create (animal). An empty object is returned, and Object. _ proto _ = animal.
One chestnut:

var animal = { eats: true }var rabbit = inherit(animal)alert(rabbit.eats) // truealert(rabbit.hasOwnProperty('eats')) // false, from prototype

Let's take a look at its principles:

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

(1) A new function is created, and the function does not set any attributes for this. In this case, 'new F' creates an empty object.
(2) 'F. prototype' is set to proto
(3) 'new F creates an empty object, '_ proto _ = F. prototype' of the object'
(4) Bingo! We get 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 optionsfunction Menu (options) {options. width = options. width | 300 // set default value //...}

... However, changing the parameter value may produce some incorrect results, because options may be used in external code. One solution is to clone the options object, copy all attributes to a new object, and modify the attributes in the new object,
How can we use inheritance to solve this problem? P.S. options can be added but cannot be deleted.
Solution
You can inherit options and modify or add new attributes in its subclass.

function inherit(proto) { function F() {} F.prototype = proto return new F}function Menu(options) { var opts = inherit(options) opts.width = opts.width || 300 // ...}

All operations are valid only in sub-objects. When the Menu method ends, external code can still use the unmodified options object. The delete operation is very important here. If width is an attribute in prototype, delete opts. width will not play any role.

5. hasOwnProperty
All objects have the hasOwnProperty function, which can be used to detect whether an object itself belongs to a prototype.
One chestnut:

function Rabbit(name) { this.name = name}Rabbit.prototype = { eats: true }var rabbit = new Rabbit('John')alert( rabbit.hasOwnProperty('eats') ) // false, in prototypealert( rabbit.hasOwnProperty('name') ) // true, in object

6. Looping with/without inherited properties
For... in loops output all attributes of an object, including its own and prototype.

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"}

HasOwnProperty can be used to filter out attributes of the object:

function Rabbit(name) { this.name = name}Rabbit.prototype = { eats: true }var rabbit = new Rabbit('John')for(var p in rabbit) { if (!rabbit.hasOwnProperty(p)) continue // filter out "eats" alert (p + " = " + rabbit[p]) // outputs only "name"}

7. Summary
JavaScript uses a special property proto to implement inheritance.
When accessing an object's properties, if the interpreter cannot be found in the object, it will go to the object's prototype to continue searching. For function properties, this points to this object, instead of its prototype.
Assign obj. prop = value to delete obj. prop
Manage proto:
Chrome and FireFox can directly access the _ proto _ attribute of the Object. Most modern browsers support read-only access using Object. getPrototypeOf (obj.
Object. create (proto) can use the given proto to generate empty sub-objects, or use the following code to achieve the same function:

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

Other methods:
For... in loops output all attributes of an object (including its own and its prototype) and the prototype chain of the object.
If a property prop belongs to the object obj, obj. hasOwnProperty (prop) returns true; otherwise, 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.