SlideShare une entreprise Scribd logo
1  sur  42
Télécharger pour lire hors ligne
JS进阶
__proto__ and prototype

李志业@FE
Inheritance

•

no classes!

•

prototype-based inheritance
__proto__
•

internal property, aka [[prototype]] !
•

the prototype of this object.!

•

exists internally, but hidden in some browsers!

•

property search!

•

prototype chain: inheritance, instanceof
1
2
3
4
5
6

var animal = { eats: true }!
var rabbit = { jumps: true }!
!
rabbit.__proto__ = animal // inherit!
!
alert(rabbit.eats) // true!
property search
[[Get]](P)
When the [[Get]] method of O is called with property
name P, the following steps are taken:!
1. If O doesn't have a property with name P, go to step 4.!
2. Get the value of the property.!
3. Return Result(2).!
4. If the [[Prototype]] of O is null, return undefined.!
5. Call the [[Get]] method of [[Prototype]] with property
name P.!
6. Return Result(5).
new

new F() create object with!
!

obj.__proto__ = F.prototype
How
1. Create a new native ECMAScript object. !
2. The [[Prototype]] property of the newly constructed
object is set to the Object prototype object. !
3. The [[Class]] property of the newly constructed
object is set to "Object". !
4. The newly constructed object has no [[Value]]
property. !
5. Return the newly created native object.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17

function Animal() {!
this.eat = true;!
}!
var cat = new Animal();!
!
console.log(cat.eat);!
Animal.prototype.jump = true;!
console.log(cat.jump);!
!
Animal.prototype = {!
bark: true!
};!
!
var dog = new Animal();!
!
console.log(cat.bark);!
console.log(dog.bark);!
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17

function Animal() {!
this.eat = true;!
}!
var cat = new Animal();!
!
console.log(cat.eat);!
Animal.prototype.jump = true;!
console.log(cat.jump);!
!
Animal.prototype = {!
bark: true!
};!
!
var dog = new Animal();!
!
console.log(cat.bark);!
console.log(dog.bark);!

Run
rabbit
rabbit
Animal
prototype
rabbit
Animal
prototype

{}
__proto__
rabbit
Animal
prototype

{}
__proto__

Object.prototype!
__proto__

null
new Animal()

rabbit

Animal
prototype

{}
__proto__

Object.prototype!
__proto__

null
cat
eats

TRUE

__proto__
new Animal()

rabbit

Animal
prototype

{}
__proto__

Object.prototype!
__proto__

null
cat
eats

TRUE

__proto__
new Animal()

rabbit

Animal
prototype

{}
{}
jump

TRUE

__proto__
__proto__

Object.prototype!
__proto__

null
cat
eats

TRUE

__proto__
new Animal()

rabbit

Animal
prototype

{}
{}
jump

{}
TRUE

bark

__proto__
__proto__

__proto__

Object.prototype!
__proto__

null

TRUE
cat
eats

TRUE

__proto__
new Animal()

rabbit

Animal
prototype

{}
{}
jump

{}
TRUE

bark

__proto__
__proto__

__proto__

Object.prototype!
__proto__

null

TRUE
cat
eats

dog
TRUE
__proto__

__proto__
new Animal()

rabbit

Animal
prototype

{}
{}
jump

{}
TRUE

bark

__proto__
__proto__

__proto__

Object.prototype!
__proto__

null

TRUE
conclusion
•

search for property along the __proto__ chain!

•

property assign not affect the __proto__ property!

•

__proto__ was created at the moment of the object’s
creation!

•

replacing prototype property of the constructor does
not affect the prototype of already created objects
Object.create
•

creates a new object with the specified prototype
object and properties.!

•

Syntax!
!

Object.create(proto [, propertiesObject ])
1
2
3
4
5

var animal = { eats: true }!
rabbit = Object.create(animal);!
!
// true!
rabbit
console.log(rabbit.eats);!

rabbit
1
2
3
4
5

var animal = { eats: true }!
rabbit = Object.create(animal);!
!
// true!
rabbit
console.log(rabbit.eats);!

animal
rabbit

eat

__proto__

TRUE
1
2
3
4
5

var animal = { eats: true }!
rabbit = Object.create(animal);!
!
// true!
rabbit
console.log(rabbit.eats);!

animal
rabbit

eat

TRUE

__proto__

Object.prototype!
__proto__

null
1
2
3
4
5

var animal = { eats: true }!
rabbit = Object.create(animal);!
!
// true!
rabbit
console.log(rabbit.eats);!

animal
rabbit

eat

TRUE

__proto__

Object.prototype!
__proto__

null
rabbit
__proto__

1
2
3
4
5

var animal = { eats: true }!
rabbit = Object.create(animal);!
!
// true!
rabbit
console.log(rabbit.eats);!

animal
rabbit

eat

TRUE

__proto__

Object.prototype!
__proto__

null
rabbit
__proto__

1
2
3
4
5

var animal = { eats: true }!
rabbit = Object.create(animal);!
!
// true!
rabbit
console.log(rabbit.eats);!

animal
rabbit

eat

TRUE

__proto__

Object.prototype!
__proto__

null
How
Object.create ( O [, Properties] ) # Ⓣ Ⓡ!
1. If Type(O) is not Object or Null throw a TypeError exception.!
2. Let obj be the result of creating a new object as if by the
expression new Object() where Object is the standard builtin constructor with that name!
3. Set the [[Prototype]] internal property of obj to O.!
4. If the argument Properties is present and not undefined, add
own properties to obj as if by calling the standard built-in
function Object.defineProperties with arguments obj and
Properties.!
5. Return obj.
instanceof
logic behind obj instanceof F
1. Get obj.__proto__!
2. Compare obj.__proto__ against F.prototype!
3. If no match then set temporarily obj =
obj.__proto__ and repeat step 2 until either match
is found or the chain ends.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20

function Animal() {!
this.name = 'wangcai';!
}!
function Dog() {}!
Dog.prototype = new Animal();!
!
var d1 = new Dog();!
!
console.log(d1.name);!
console.log(d1 instanceof Animal);!
!
// change the prototype of Class!
Dog.prototype = {!
name: 'yingcai'!
};!
!
// now instanceof ??!
console.log(d1 instanceof Dog);!
console.log(d1 instanceof Animal);!
console.log(Animal.prototype.__proto__ === Object.prototype);!
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20

function Animal() {!
this.name = 'wangcai';!
}!
function Dog() {}!
Dog.prototype = new Animal();!
!
var d1 = new Dog();!
!
console.log(d1.name);!
console.log(d1 instanceof Animal);!
!
// change the prototype of Class!
Dog.prototype = {!
name: 'yingcai'!
};!
!
// now instanceof ??!
console.log(d1 instanceof Dog);!
console.log(d1 instanceof Animal);!
console.log(Animal.prototype.__proto__ === Object.prototype);!

Run
Dog

d1
prototype

rabbit

__proto__

__proto__

Animal

Dog.prototype
name

‘wangcai’

__proto__

prototype
__proto__

Animal.prototype!
__proto__

Function.prototype!
__proto__

Object.prototype
__proto__

null
Dog

d1
prototype

rabbit

__proto__

__proto__

Dog.prototype
name

Dog.prototype

‘wangcai’

__proto__

name
__proto__

Animal.prototype!
__proto__

Object.prototype
__proto__

null

‘wangcai’
Will instanceof

always work?
Lies when cross window or iframe
1
2
3
4
5
6
7
8
9 !
10
11
12

<iframe id="fr" ></iframe>!
<script>!
var fr = document.getElementById('fr');!
var arr = [];!
var ArrayFr = fr.contentWindow.Array;!
var arr2 = new ArrayFr();!
console.log(Object.prototype.toString.call(arr));!
console.log(Object.prototype.toString.call(arr2));!
console.log(arr instanceof Array);!
console.log(arr instanceof ArrayFr);!
</script>!
1
2
3
4
5
6
7
8
9 !
10
11
12

<iframe id="fr" ></iframe>!
<script>!
var fr = document.getElementById('fr');!
var arr = [];!
var ArrayFr = fr.contentWindow.Array;!
var arr2 = new ArrayFr();!
console.log(Object.prototype.toString.call(arr));!
console.log(Object.prototype.toString.call(arr2));!
console.log(arr instanceof Array);!
console.log(arr instanceof ArrayFr);!
</script>!

Run
Object.getPrototypeOf

•

preferred way to access the __proto__ of an object.!

•

readOnly
Reference
•

[[prototype]] http://blog.tsnrose.com/ecmascript262-3#_Prototype_!

•

Prototypal inheritance http://javascript.info/tutorial/inheritance !

•

http://dmitrysoshnikov.com/ecmascript/chapter-7-2-oop-ecmascriptimplementation/#prototype!

•

[[Get]](P) http://blog.tsnrose.com/ecmascript262-3#a-8.6.2.1!

•

new Object() http://blog.tsnrose.com/ecmascript262-3#a-15.2.2.1
Q&A

•

relation of __proto__ and prototype

Contenu connexe

Tendances

Clojure beasts-euroclj-2014
Clojure beasts-euroclj-2014Clojure beasts-euroclj-2014
Clojure beasts-euroclj-2014
Renzo Borgatti
 
Bdd: Tdd and beyond the infinite
Bdd: Tdd and beyond the infiniteBdd: Tdd and beyond the infinite
Bdd: Tdd and beyond the infinite
Giordano Scalzo
 
JDK8 : parallel programming made (too ?) easy
JDK8 : parallel programming made (too ?) easyJDK8 : parallel programming made (too ?) easy
JDK8 : parallel programming made (too ?) easy
José Paumard
 
Google Guava & EMF @ GTUG Nantes
Google Guava & EMF @ GTUG NantesGoogle Guava & EMF @ GTUG Nantes
Google Guava & EMF @ GTUG Nantes
mikaelbarbero
 

Tendances (20)

Py.test
Py.testPy.test
Py.test
 
Google Guava
Google GuavaGoogle Guava
Google Guava
 
The Sincerest Form of Flattery
The Sincerest Form of FlatteryThe Sincerest Form of Flattery
The Sincerest Form of Flattery
 
Free your lambdas
Free your lambdasFree your lambdas
Free your lambdas
 
Testes pythonicos com pytest
Testes pythonicos com pytestTestes pythonicos com pytest
Testes pythonicos com pytest
 
Real world gobbledygook
Real world gobbledygookReal world gobbledygook
Real world gobbledygook
 
Python 3000
Python 3000Python 3000
Python 3000
 
Clojure beasts-euroclj-2014
Clojure beasts-euroclj-2014Clojure beasts-euroclj-2014
Clojure beasts-euroclj-2014
 
Google Guava - Core libraries for Java & Android
Google Guava - Core libraries for Java & AndroidGoogle Guava - Core libraries for Java & Android
Google Guava - Core libraries for Java & Android
 
Pytest - testing tips and useful plugins
Pytest - testing tips and useful pluginsPytest - testing tips and useful plugins
Pytest - testing tips and useful plugins
 
Using spl tools in your code
Using spl tools in your codeUsing spl tools in your code
Using spl tools in your code
 
Bdd: Tdd and beyond the infinite
Bdd: Tdd and beyond the infiniteBdd: Tdd and beyond the infinite
Bdd: Tdd and beyond the infinite
 
JDK8 : parallel programming made (too ?) easy
JDK8 : parallel programming made (too ?) easyJDK8 : parallel programming made (too ?) easy
JDK8 : parallel programming made (too ?) easy
 
Don't do this
Don't do thisDon't do this
Don't do this
 
Pytest: escreva menos, teste mais
Pytest: escreva menos, teste maisPytest: escreva menos, teste mais
Pytest: escreva menos, teste mais
 
Google Guava & EMF @ GTUG Nantes
Google Guava & EMF @ GTUG NantesGoogle Guava & EMF @ GTUG Nantes
Google Guava & EMF @ GTUG Nantes
 
Java 8, Streams & Collectors, patterns, performances and parallelization
Java 8, Streams & Collectors, patterns, performances and parallelizationJava 8, Streams & Collectors, patterns, performances and parallelization
Java 8, Streams & Collectors, patterns, performances and parallelization
 
Text Manipulation with/without Parsec
Text Manipulation with/without ParsecText Manipulation with/without Parsec
Text Manipulation with/without Parsec
 
Free your lambdas
Free your lambdasFree your lambdas
Free your lambdas
 
Google Guava
Google GuavaGoogle Guava
Google Guava
 

Similaire à __proto__-and-prototype

Use the following code for the tasks public class Animal .pdf
Use the following code for the tasks  public class Animal .pdfUse the following code for the tasks  public class Animal .pdf
Use the following code for the tasks public class Animal .pdf
adityknits
 
Prototype 120102020133-phpapp02
Prototype 120102020133-phpapp02Prototype 120102020133-phpapp02
Prototype 120102020133-phpapp02
plutoone TestTwo
 
Introduction to javascript and yoolkui
Introduction to javascript and yoolkuiIntroduction to javascript and yoolkui
Introduction to javascript and yoolkui
Khou Suylong
 
Front end fundamentals session 1: javascript core
Front end fundamentals session 1: javascript coreFront end fundamentals session 1: javascript core
Front end fundamentals session 1: javascript core
Web Zhao
 

Similaire à __proto__-and-prototype (20)

Prototypes
PrototypesPrototypes
Prototypes
 
from Ruby to Objective-C
from Ruby to Objective-Cfrom Ruby to Objective-C
from Ruby to Objective-C
 
Use the following code for the tasks public class Animal .pdf
Use the following code for the tasks  public class Animal .pdfUse the following code for the tasks  public class Animal .pdf
Use the following code for the tasks public class Animal .pdf
 
Understanding Prototypal Inheritance
Understanding Prototypal InheritanceUnderstanding Prototypal Inheritance
Understanding Prototypal Inheritance
 
Prototype 120102020133-phpapp02
Prototype 120102020133-phpapp02Prototype 120102020133-phpapp02
Prototype 120102020133-phpapp02
 
JavaScript Classes and Inheritance
JavaScript Classes and InheritanceJavaScript Classes and Inheritance
JavaScript Classes and Inheritance
 
JavaScript Essentials
JavaScript EssentialsJavaScript Essentials
JavaScript Essentials
 
Prototype
PrototypePrototype
Prototype
 
Introduction to javascript and yoolkui
Introduction to javascript and yoolkuiIntroduction to javascript and yoolkui
Introduction to javascript and yoolkui
 
Es.next
Es.nextEs.next
Es.next
 
Java Script Workshop
Java Script WorkshopJava Script Workshop
Java Script Workshop
 
Ceylon idioms by Gavin King
Ceylon idioms by Gavin KingCeylon idioms by Gavin King
Ceylon idioms by Gavin King
 
Front end fundamentals session 1: javascript core
Front end fundamentals session 1: javascript coreFront end fundamentals session 1: javascript core
Front end fundamentals session 1: javascript core
 
Javascript tid-bits
Javascript tid-bitsJavascript tid-bits
Javascript tid-bits
 
Basic inheritance in JavaScript
Basic inheritance in JavaScriptBasic inheritance in JavaScript
Basic inheritance in JavaScript
 
Plugin jQuery, Design Patterns
Plugin jQuery, Design PatternsPlugin jQuery, Design Patterns
Plugin jQuery, Design Patterns
 
Autoboxing And Unboxing In Java
Autoboxing And Unboxing In JavaAutoboxing And Unboxing In Java
Autoboxing And Unboxing In Java
 
0003 es5 핵심 정리
0003 es5 핵심 정리0003 es5 핵심 정리
0003 es5 핵심 정리
 
Exploring Ceylon with Gavin King - JUG BB Talk - Belrin 2014
Exploring Ceylon with Gavin King - JUG BB Talk - Belrin 2014Exploring Ceylon with Gavin King - JUG BB Talk - Belrin 2014
Exploring Ceylon with Gavin King - JUG BB Talk - Belrin 2014
 
justbasics.pdf
justbasics.pdfjustbasics.pdf
justbasics.pdf
 

Dernier

EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptxEIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
Earley Information Science
 
Artificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and MythsArtificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and Myths
Joaquim Jorge
 

Dernier (20)

Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)
 
Driving Behavioral Change for Information Management through Data-Driven Gree...
Driving Behavioral Change for Information Management through Data-Driven Gree...Driving Behavioral Change for Information Management through Data-Driven Gree...
Driving Behavioral Change for Information Management through Data-Driven Gree...
 
Understanding Discord NSFW Servers A Guide for Responsible Users.pdf
Understanding Discord NSFW Servers A Guide for Responsible Users.pdfUnderstanding Discord NSFW Servers A Guide for Responsible Users.pdf
Understanding Discord NSFW Servers A Guide for Responsible Users.pdf
 
The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024
 
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
 
How to convert PDF to text with Nanonets
How to convert PDF to text with NanonetsHow to convert PDF to text with Nanonets
How to convert PDF to text with Nanonets
 
Breaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path MountBreaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path Mount
 
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptxEIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
 
Artificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and MythsArtificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and Myths
 
Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024
 
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
 
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
 
Automating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps ScriptAutomating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps Script
 
Boost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivityBoost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivity
 
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
 
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
 
Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024
 
Tata AIG General Insurance Company - Insurer Innovation Award 2024
Tata AIG General Insurance Company - Insurer Innovation Award 2024Tata AIG General Insurance Company - Insurer Innovation Award 2024
Tata AIG General Insurance Company - Insurer Innovation Award 2024
 
[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdf[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdf
 
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law DevelopmentsTrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
 

__proto__-and-prototype