Home Web Front-end JS Tutorial Basic Learning Tutorial on Prototypal Inheritance in JavaScript_Basic Knowledge

Basic Learning Tutorial on Prototypal Inheritance in JavaScript_Basic Knowledge

May 16, 2016 pm 03:01 PM
javascript prototype inherit

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

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 accessing the rabbit object, if the interpreter cannot find the attribute in rabbit, then it will follow the __proto__ chain and look for
in the animal object. The __proto__ attribute in the chestnut is only accessible in Chrome and FireFox. Please see a chestnut:

var animal = { eats: true }
var rabbit = { jumps: true }

rabbit.__proto__ = animal // inherit

alert(rabbit.eats) // true

Copy after login

The eats attribute is accessed from the animal object.
If the property has been found in the rabbit object, the proto property will not be checked.
Another example, when the subclass also has the eats attribute, the one in the parent class will not be accessed.

var animal = { eats: true }
var fedUpRabbit = { eats: false}

fedUpRabbit.__proto__ = animal 

alert(fedUpRabbit.eats) // false

Copy after login

You can also add a function in animal, and it can also be accessed in rabbit.

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


var rabbit = {
 jump: function() { /* something */ }
}

rabbit.__proto__ = animal 

Copy after login

(1) rabbit.eat():
The rabbit.eat() function is executed in the following two steps:
First, the interpreter looks for rabbit.eat. There is no eat function in rabbit, so it looks up rabbit.__proto__ and finds it in animal.
The function is run with this = rabbit. The this value has absolutely nothing to do with the __proto__ attribute.
Therefore, this.full = true in rabbit:
Let's see what new discovery we have here. An object calls a parent class function, but this still points to the object itself. This is inheritance.
The object referenced by __proto__ is called a prototype, and animal is rabbit’s prototype (Translator’s Note: This is because rabbit’s __proto__ attribute refers to animal’s prototype attribute)
(2) Search when reading, not when writing
When reading an object, such as this.prop, the interpreter looks for the property in its prototype.
When setting a property value, such as this.prop = value, there is no reason to look for it, the property (prop) will be added directly to the object (here this). delete obj.prop is similar, it only deletes the properties of the object itself, and the properties in the prototype remain intact.
(3) About proto
If you're reading the guide, what we call __proto__ here is represented as [[Prototype]] in the guide. The double brackets are important because there is another attribute called prototype.

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

Object.ceate(prop[,props])
Copy after login

Create an empty object with the given proto:

var animal = { eats: true }

rabbit = Object.create(animal)

alert(rabbit.eats) // true

Copy after login

The above code creates an empty rabbit object and sets the prototype 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

Copy after login

The second parameter props of the Object.creat function is optional, which allows setting properties like a new object. It is omitted here 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 do not have direct access to the __proto__ attribute.

var animal = {
 eats: true
}

rabbit = Object.create(animal)

alert( Object.getPrototypeOf(rabbit) === animal ) // true

Copy after login

Modern browsers allow reading the __proto__ attribute value, but not setting 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 through the new keyword.
A chestnut:

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

var rabbit = new Rabbit('John')

alert(rabbit.name) // John

Copy after login

The new operation sets the prototype's attributes to the __proto__ attribute of the rabbit object.
Let's take a look at how it works, for example, the new Rabbit object, and Rabbit inherits from 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

Copy after login

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 simulated by the following code:

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

inherit(animal) is completely equivalent to Object.create(animal), returning an empty object, and object.__proto__ = animal.
A chestnut:

var animal = { eats: true }

var rabbit = inherit(animal)

alert(rabbit.eats) // true
alert(rabbit.hasOwnProperty('eats')) // false, from prototype

Copy after login

Let’s take a look at how it works:

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

(1) 创建了一个新函数,函数没有向this设置任何属性,以此`new F` 会创建一个空对象。
(2) `F.prototype`被设置为proto
(3) `new` F创建了一个空对象,对象的`__proto__ = F.prototype`
(4) Bingo! 我们得到了一个继承`proto`的空对象
这个函数广泛适用于各种库和框架之中。
你的函数接受了一个带有options 的对象

/* options contains menu settings: width, height etc */
function Menu(options) {
 // ...
}
你想设置某些options
function Menu(options) {
 options.width = options.width || 300 // set default value
 // ...
}
Copy after login

。。。但是改变参数值可能会产生一些错误的结果,因为options可能会在外部代码中使用。一个解决办法就是克隆options对象,复制所有的属性到一个新的对象中,在新对象中修改,
怎样用继承来解决这个问题呢? P.S. options可以添加设设置,但是不能被删除。
Solution
你可以继承options,并且在它的子类的中修改或者添加新的属性。

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

function Menu(options) {
 var opts = inherit(options)
 opts.width = opts.width || 300
 // ...
}

Copy after login

所有的操作只在子对象中有效,当Menu方法结束时,外部代码仍然可以使用没有修改的过的options对象。delete操作在这里非常重要,如果width是一个prototype中的属性,delete opts.width不会产生任何作用

5. hasOwnProperty
所有的对象都有hasOwnProperty函数,它可以用来检测一个属性是否对象自身还是属于原型
一个栗子:

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

Copy after login

6. Looping with/without inherited properties
for..in循环输出一个对象的所有属性,包括自身的和原型的。

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

Copy after login

用hasOwnProperty可以过滤得到属于对象自己的属性:

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

Copy after login

7. Summary
JavaScript是通过一个特殊的属性proto来实现继承的
当访问一个对象的属性时,如果解释器不能在对象中找到,它就会去对象的原型中继续寻找 对函数属性来说,this指向这个对象,而不是它的原型。
赋值obj.prop = value, 删除delete obj.prop
管理proto:
Chrome和FireFox可以直接访问对象的__proto__属性,大多数现代浏览器支持用Object.getPrototypeOf(obj)只读访问。
Object.create(proto) 可以用给定的proto生成空的子对象,或者通过如下代码达到相同的功能:

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

其他方法:
for..in循环输出一个对象的所有属性(包括自身的和原型的)和对象的原型链。
如果一个属性prop属于对象obj那么obj.hasOwnProperty(prop)返回true,否则返回false。

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

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
WWE 2K25: How To Unlock Everything In MyRise
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Detailed explanation of C++ function inheritance: How to use 'base class pointer' and 'derived class pointer' in inheritance? Detailed explanation of C++ function inheritance: How to use 'base class pointer' and 'derived class pointer' in inheritance? May 01, 2024 pm 10:27 PM

In function inheritance, use "base class pointer" and "derived class pointer" to understand the inheritance mechanism: when the base class pointer points to the derived class object, upward transformation is performed and only the base class members are accessed. When a derived class pointer points to a base class object, a downward cast is performed (unsafe) and must be used with caution.

How do inheritance and polymorphism affect class coupling in C++? How do inheritance and polymorphism affect class coupling in C++? Jun 05, 2024 pm 02:33 PM

Inheritance and polymorphism affect the coupling of classes: Inheritance increases coupling because the derived class depends on the base class. Polymorphism reduces coupling because objects can respond to messages in a consistent manner through virtual functions and base class pointers. Best practices include using inheritance sparingly, defining public interfaces, avoiding adding data members to base classes, and decoupling classes through dependency injection. A practical example showing how to use polymorphism and dependency injection to reduce coupling in a bank account application.

Detailed explanation of C++ function inheritance: How to debug errors in inheritance? Detailed explanation of C++ function inheritance: How to debug errors in inheritance? May 02, 2024 am 09:54 AM

Inheritance error debugging tips: Ensure correct inheritance relationships. Use the debugger to step through the code and examine variable values. Make sure to use the virtual modifier correctly. Examine the inheritance diamond problem caused by hidden inheritance. Check for unimplemented pure virtual functions in abstract classes.

Detailed explanation of C++ function inheritance: How to understand the 'is-a' and 'has-a' relationship in inheritance? Detailed explanation of C++ function inheritance: How to understand the 'is-a' and 'has-a' relationship in inheritance? May 02, 2024 am 08:18 AM

Detailed explanation of C++ function inheritance: Master the relationship between "is-a" and "has-a" What is function inheritance? Function inheritance is a technique in C++ that associates methods defined in a derived class with methods defined in a base class. It allows derived classes to access and override methods of the base class, thereby extending the functionality of the base class. "is-a" and "has-a" relationships In function inheritance, the "is-a" relationship means that the derived class is a subtype of the base class, that is, the derived class "inherits" the characteristics and behavior of the base class. The "has-a" relationship means that the derived class contains a reference or pointer to the base class object, that is, the derived class "owns" the base class object. SyntaxThe following is the syntax for how to implement function inheritance: classDerivedClass:pu

Introduction to the new map of Genshin Impact version 4.4 Introduction to the new map of Genshin Impact version 4.4 Jan 31, 2024 pm 06:36 PM

Introducing the new map of Genshin Impact version 4.4. Friends, Genshin Impact 4.4 version also ushered in the Sea Lantern Festival in Liyue. At the same time, a new map area will be launched in version 4.4 called Shen Yu Valley. According to the information provided, Shen Yugu is actually part of Qiaoying Village, but players are more accustomed to calling it Shen Yugu. Now let me introduce the new map to you. Introduction to the new map of Genshin Impact version 4.4. Version 4.4 will open "Chenyu Valley·Shanggu", "Chenyu Valley·Nanling" and "Laixin Mountain" in the north of Liyue. Teleportation anchor points have been opened for travelers in "Chenyu Valley·Shanggu" . ※After completing the prologue of the Demon God Quest·Act 3: The Dragon and the Song of Freedom, the teleportation anchor point will be automatically unlocked. 2. Qiaoyingzhuang When the warm spring breeze once again caressed the mountains and fields of Chenyu, the fragrant

'Introduction to Object-Oriented Programming in PHP: From Concept to Practice' 'Introduction to Object-Oriented Programming in PHP: From Concept to Practice' Feb 25, 2024 pm 09:04 PM

What is object-oriented programming? Object-oriented programming (OOP) is a programming paradigm that abstracts real-world entities into classes and uses objects to represent these entities. Classes define the properties and behavior of objects, and objects instantiate classes. The main advantage of OOP is that it makes code easier to understand, maintain and reuse. Basic Concepts of OOP The main concepts of OOP include classes, objects, properties and methods. A class is the blueprint of an object, which defines its properties and behavior. An object is an instance of a class and has all the properties and behaviors of the class. Properties are characteristics of an object that can store data. Methods are functions of an object that can operate on the object's data. Advantages of OOP The main advantages of OOP include: Reusability: OOP can make the code more

C++ function inheritance explained: When should inheritance not be used? C++ function inheritance explained: When should inheritance not be used? May 04, 2024 pm 12:18 PM

C++ function inheritance should not be used in the following situations: When a derived class requires a different implementation, a new function with a different implementation should be created. When a derived class does not require a function, it should be declared as an empty class or use private, unimplemented base class member functions to disable function inheritance. When functions do not require inheritance, other mechanisms (such as templates) should be used to achieve code reuse.

Java Interfaces and Abstract Classes: The Road to Programming Heaven Java Interfaces and Abstract Classes: The Road to Programming Heaven Mar 04, 2024 am 09:13 AM

Interface: An implementationless contract interface defines a set of method signatures in Java but does not provide any concrete implementation. It acts as a contract that forces classes that implement the interface to implement its specified methods. The methods in the interface are abstract methods and have no method body. Code example: publicinterfaceAnimal{voideat();voidsleep();} Abstract class: Partially implemented blueprint An abstract class is a parent class that provides a partial implementation that can be inherited by its subclasses. Unlike interfaces, abstract classes can contain concrete implementations and abstract methods. Abstract methods are declared with the abstract keyword and must be overridden by subclasses. Code example: publicabstractcla

See all articles