SlideShare ist ein Scribd-Unternehmen logo
1 von 60
Downloaden Sie, um offline zu lesen
Object-oriented 
Javascript 
Daniel Ku (http://kjunine.net/)
Primitives and 
Objects
“Is Everything 
in JavaScript 
an object?”
WRONG!
Primitives 
» string 
» number 
» boolean 
» undefined 
» null 
Everything else is object.
“WHAT? 
Strings have 
properties and methods!”
var p = 'hello'; 
p.test = 'test'; 
console.log(p.test); // ? 
var o = new String('hello'); 
o.test = 'test'; 
console.log(o.test); // ?
var p = 'hello'; 
p.test = 'test'; 
console.log(p.test); // undefined 
var o = new String('hello'); 
o.test = 'test'; 
console.log(o.test); // test
typeof 'hello'; // string 
typeof new String('hello'); // object 
typeof 10 // number 
typeof new Number(10); // object 
typeof false; // boolean 
typeof new Boolean(true); // object 
typeof undefined; // undefined 
typeof null; // object ???
HOW 
to create an object?
Factory Functions
var createPerson = function(firstName, lastName) { 
return { 
firstName: firstName, 
lastName: lastName, 
sayHi: function() { 
return 'Hi there'; 
} 
}; 
}; 
var john = createPerson('John', 'Doe'); 
var jane = createPerson('Jane', 'Doe');
IT WORKS! BUT, 
BAD PRACTICE!
The this keyword
this 
is 
» window in global context 
» the object in an object
var name = 'Jane'; 
var greet = function() { 
return 'My name is ' + this.name; 
} 
var person = { 
name: 'John', 
greet: greet 
}; 
greet(); // ? 
person.greet(); // ?
var name = 'Jane'; 
var greet = function() { 
return 'My name is ' + this.name; 
} 
var person = { 
name: 'John', 
greet: greet 
}; 
greet(); // My name is Jane 
person.greet(); // My name is John
var requestAsync = function(url, callback) { 
var data = 10; 
callback(data); 
}; 
var requestor = { 
value: 20, 
process: function(data) { 
var sum = this.value + data; 
console.log(sum); 
}, 
request: function() { 
var url = 'http://example.com'; 
requestAsync(url, this.process); 
} 
}; 
requestor.request(); // ?
var requestAsync = function(url, callback) { 
var data = 10; 
callback(data); 
}; 
var requestor = { 
value: 20, 
process: function(data) { 
var sum = this.value + data; 
console.log(sum); 
}, 
request: function() { 
var url = 'http://example.com'; 
requestAsync(url, this.process); 
} 
}; 
requestor.request(); // NaN
Function.prototype.bind 
» reference 
» es5-shim
var requestAsync = function(url, callback) { 
var data = 10; 
callback(data); 
}; 
var requestor = { 
value: 20, 
process: function(data) { 
var sum = this.value + data; 
console.log(sum); 
}, 
request: function() { 
var url = 'http://example.com'; 
requestAsync(url, this.process.bind(this)); 
} 
}; 
requestor.request(); // 30
Constructor 
Functions
var Person = function(firstName, lastName) { 
this.firstName = firstName; 
this.lastName = lastName; 
this.sayHi = function() { 
return 'Hi~'; 
}; 
}; 
var person = new Person('John', 'Doe');
Also, 
BAD PRACTICE! 
Do like next.
var Person = function(firstName, lastName) { 
this.firstName = firstName; 
this.lastName = lastName; 
}; 
Person.prototype.sayHi = function() { 
return 'Hi~'; 
}; 
var person = new Person('John', 'Doe');
The Prototype
Object.getPrototypeOf 
» reference 
» es5-shim
person.constructor === Person; // true 
person.__proto__ === Person.prototype; // true 
Object.getPrototypeOf(person) 
=== Person.prototype; // true
person.hasOwnProperty('firstName'); // true 
person.hasOwnProperty('lastName'); // true 
person.hasOwnProperty('sayHi'); // false 
person.constructor 
.prototype 
.hasOwnProperty('sayHi'); // true
Properties and 
Property 
Descriptors
var person = {}; 
Object.defineProperty(person, 'firstName', { 
// descriptor object (data descriptor) 
value: 'John', 
writable: true 
}); 
Object.defineProperty(person, 'lastName', { 
value: 'Doe', 
writable: false 
}); 
person.firstName; // 'John' 
person.lastName; // 'Doe'
person.firstName = 'Jane'; 
person.firstName; // 'Jane' 
person.lastName = 'Dummy'; 
person.lastName; // 'Doe'
var person = {}; 
Object.defineProperties(person, { 
firstName: { 
value: 'John', 
writable: true 
}, 
lastName: { 
value: 'Doe', 
writable: true 
}, 
fullName: { 
// accessor descriptor 
get: function() { 
return this.firstName + ' ' + this.lastName; 
}, 
set: function(value) { 
var splits = value.split(' '); 
this.firstName = splits[0]; 
this.lastName = splits[1]; 
} 
} 
});
person.fullName; // 'John Doe' 
person.fullName = 'Jane Eyre' 
person.firstName; // 'Jane' 
person.lastName; // 'Eyre' 
person.fullName; // 'Jane Eyre'
var person = {}; 
Object.defineProperty(person, 'firstName', { 
value: 'John', 
enumerable: true 
}); 
Object.defineProperty(person, 'lastName', { 
value: 'Doe', 
enumerable: false 
}); 
for (var key in person) { 
console.log(key, '=>' , person[key]); 
} 
// 'firstName => John'
Object.defineProperty 
» Property Descriptors 
» Data Descriptors 
» Accessor Descriptors 
» reference 
» es5-shim
Common Keys of Descriptors 
» configurable (default: false) 
» enumerable (default: false)
Keys of Data Descriptors 
» value (default: undefined) 
» writable (default: false)
Keys of Accessor Descriptors 
» get (default: undefined) 
» set (default: undefined)
Constructors and 
the Prototype 
REVISITED
var Person = function(firstName, lastName) { 
Object.defineProperty(this, 'firstName', { 
value: firstName, 
writable: true, 
enumerable: true 
}); 
Object.defineProperty(this, 'lastName', { 
value: lastName, 
writable: true, 
enumerable: true 
}); 
};
Object.defineProperties(Person.prototype, { 
sayHi: { 
value: function() { 
return 'Hi there'; 
} 
}, 
fullName: { 
get: function() { 
return this.firstName + ' ' + this.lastName; 
}, 
enumerable: true 
} 
}); 
var person = new Person('John', 'Doe');
HOW 
to do inheritance?
Prototypical Inheritance
Object.create 
» reference 
» es5-shim
var person = { 
firstName: 'John', 
lastName: 'Doe' 
}; 
var employee = Object.create(person); 
Object.getPrototypeOf(employee) === person; // true
Object.getOwnPropertyDescriptor 
» reference 
» es5-shim
var Person = function(firstName, lastName) { 
this.firstName = firstName; 
this.lastName = lastName; 
}; 
Person.prototype.sayHi = function() { 
return 'Hi~'; 
}; 
var person = new Person('John', 'Doe'); 
Object.getOwnPropertyDescriptor(Person.prototype, 'sayHi'); 
// {value: function, writable: true, enumerable: true, configurable: true} 
Object.getOwnPropertyDescriptor(person, 'firstName'); 
// {value: "John", writable: true, enumerable: true, configurable: true}
Let's Do Inheritance
var Person = function(firstName, lastName) { 
Object.defineProperties(this, { 
firstName: { 
value: firstName, 
writable: true, 
enumerable: true 
}, 
lastName: { 
value: lastName, 
writable: true, 
enumerable: true 
} 
}); 
}; 
Object.defineProperties(Person.prototype, { 
sayHi: { 
value: function() { 
return 'Hi there'; 
} 
}, 
fullName: { 
get: function() { 
return this.firstName + ' ' + this.lastName; 
}, 
enumerable: true 
} 
});
var Employee = function(firstName, lastName, position) { 
Person.call(this, firstName, lastName); 
Object.defineProperties(this, { 
position: { 
value: position, 
writable: true, 
enumerable: true 
} 
}); 
};
Employee.prototype = Object.create(Person.prototype, { 
sayHi: { 
value: function() { 
return Person.prototype.sayHi.call(this) + ' and here'; 
} 
}, 
fullName: { 
get: function() { 
var descriptor = Object.getOwnPropertyDescriptor(Person.prototype, 'fullName'); 
return descriptor.get.call(this) + ' ' + this.position; 
}, 
enumerable: true 
}, 
constructor: { 
value: Employee 
} 
});
var employee = new Employee('John', 'Doe', 'Manager'); 
for (var key in employee) { 
console.log(key, '=>' , employee[key]); 
} 
// 'firstName => John' 
// 'lastName => Doe' 
// 'position => Manager' 
// 'fullName => John Doe Manager'
Prototypical 
Inheritance
Object.getPrototypeOf(employee) === Employee.prototype; // true 
employee.__proto__ === Employee.prototype; // true 
employee.__proto__.__proto__ === Person.prototype; // true 
employee.__proto__.__proto__.__proto__ === Object.prototype; // true 
employee.__proto__.__proto__.__proto__.__proto__ === null; // true
References 
» Object-Oriented JavaScript on Tuts+ 
» Inheritance revisited on MDN 
» ECMA-262-5 in detail by Dmitry Soshnikov
THE END

Weitere ähnliche Inhalte

Was ist angesagt?

PHP for Adults: Clean Code and Object Calisthenics
PHP for Adults: Clean Code and Object CalisthenicsPHP for Adults: Clean Code and Object Calisthenics
PHP for Adults: Clean Code and Object CalisthenicsGuilherme Blanco
 
Object Calisthenics Adapted for PHP
Object Calisthenics Adapted for PHPObject Calisthenics Adapted for PHP
Object Calisthenics Adapted for PHPChad Gray
 
Xlab #1: Advantages of functional programming in Java 8
Xlab #1: Advantages of functional programming in Java 8Xlab #1: Advantages of functional programming in Java 8
Xlab #1: Advantages of functional programming in Java 8XSolve
 
Adding Dependency Injection to Legacy Applications
Adding Dependency Injection to Legacy ApplicationsAdding Dependency Injection to Legacy Applications
Adding Dependency Injection to Legacy ApplicationsSam Hennessy
 
Symfony2 Building on Alpha / Beta technology
Symfony2 Building on Alpha / Beta technologySymfony2 Building on Alpha / Beta technology
Symfony2 Building on Alpha / Beta technologyDaniel Knell
 
PHPUnit でよりよくテストを書くために
PHPUnit でよりよくテストを書くためにPHPUnit でよりよくテストを書くために
PHPUnit でよりよくテストを書くためにYuya Takeyama
 
The History of PHPersistence
The History of PHPersistenceThe History of PHPersistence
The History of PHPersistenceHugo Hamon
 
SfCon: Test Driven Development
SfCon: Test Driven DevelopmentSfCon: Test Driven Development
SfCon: Test Driven DevelopmentAugusto Pascutti
 
Command Bus To Awesome Town
Command Bus To Awesome TownCommand Bus To Awesome Town
Command Bus To Awesome TownRoss Tuck
 
Database Design Patterns
Database Design PatternsDatabase Design Patterns
Database Design PatternsHugo Hamon
 
PHPUnit elevato alla Symfony2
PHPUnit elevato alla Symfony2PHPUnit elevato alla Symfony2
PHPUnit elevato alla Symfony2eugenio pombi
 
Models and Service Layers, Hemoglobin and Hobgoblins
Models and Service Layers, Hemoglobin and HobgoblinsModels and Service Layers, Hemoglobin and Hobgoblins
Models and Service Layers, Hemoglobin and HobgoblinsRoss Tuck
 
Hacking Your Way To Better Security - Dutch PHP Conference 2016
Hacking Your Way To Better Security - Dutch PHP Conference 2016Hacking Your Way To Better Security - Dutch PHP Conference 2016
Hacking Your Way To Better Security - Dutch PHP Conference 2016Colin O'Dell
 
Migrating to dependency injection
Migrating to dependency injectionMigrating to dependency injection
Migrating to dependency injectionJosh Adell
 
Things I Believe Now That I'm Old
Things I Believe Now That I'm OldThings I Believe Now That I'm Old
Things I Believe Now That I'm OldRoss Tuck
 
Functional Structures in PHP
Functional Structures in PHPFunctional Structures in PHP
Functional Structures in PHPMarcello Duarte
 
Mirror, mirror on the wall: Building a new PHP reflection library (DPC 2016)
Mirror, mirror on the wall: Building a new PHP reflection library (DPC 2016)Mirror, mirror on the wall: Building a new PHP reflection library (DPC 2016)
Mirror, mirror on the wall: Building a new PHP reflection library (DPC 2016)James Titcumb
 

Was ist angesagt? (19)

Mocking Demystified
Mocking DemystifiedMocking Demystified
Mocking Demystified
 
PHP for Adults: Clean Code and Object Calisthenics
PHP for Adults: Clean Code and Object CalisthenicsPHP for Adults: Clean Code and Object Calisthenics
PHP for Adults: Clean Code and Object Calisthenics
 
Object Calisthenics Adapted for PHP
Object Calisthenics Adapted for PHPObject Calisthenics Adapted for PHP
Object Calisthenics Adapted for PHP
 
Xlab #1: Advantages of functional programming in Java 8
Xlab #1: Advantages of functional programming in Java 8Xlab #1: Advantages of functional programming in Java 8
Xlab #1: Advantages of functional programming in Java 8
 
Adding Dependency Injection to Legacy Applications
Adding Dependency Injection to Legacy ApplicationsAdding Dependency Injection to Legacy Applications
Adding Dependency Injection to Legacy Applications
 
Symfony2 Building on Alpha / Beta technology
Symfony2 Building on Alpha / Beta technologySymfony2 Building on Alpha / Beta technology
Symfony2 Building on Alpha / Beta technology
 
PHPUnit でよりよくテストを書くために
PHPUnit でよりよくテストを書くためにPHPUnit でよりよくテストを書くために
PHPUnit でよりよくテストを書くために
 
The History of PHPersistence
The History of PHPersistenceThe History of PHPersistence
The History of PHPersistence
 
SfCon: Test Driven Development
SfCon: Test Driven DevelopmentSfCon: Test Driven Development
SfCon: Test Driven Development
 
Command Bus To Awesome Town
Command Bus To Awesome TownCommand Bus To Awesome Town
Command Bus To Awesome Town
 
Min-Maxing Software Costs
Min-Maxing Software CostsMin-Maxing Software Costs
Min-Maxing Software Costs
 
Database Design Patterns
Database Design PatternsDatabase Design Patterns
Database Design Patterns
 
PHPUnit elevato alla Symfony2
PHPUnit elevato alla Symfony2PHPUnit elevato alla Symfony2
PHPUnit elevato alla Symfony2
 
Models and Service Layers, Hemoglobin and Hobgoblins
Models and Service Layers, Hemoglobin and HobgoblinsModels and Service Layers, Hemoglobin and Hobgoblins
Models and Service Layers, Hemoglobin and Hobgoblins
 
Hacking Your Way To Better Security - Dutch PHP Conference 2016
Hacking Your Way To Better Security - Dutch PHP Conference 2016Hacking Your Way To Better Security - Dutch PHP Conference 2016
Hacking Your Way To Better Security - Dutch PHP Conference 2016
 
Migrating to dependency injection
Migrating to dependency injectionMigrating to dependency injection
Migrating to dependency injection
 
Things I Believe Now That I'm Old
Things I Believe Now That I'm OldThings I Believe Now That I'm Old
Things I Believe Now That I'm Old
 
Functional Structures in PHP
Functional Structures in PHPFunctional Structures in PHP
Functional Structures in PHP
 
Mirror, mirror on the wall: Building a new PHP reflection library (DPC 2016)
Mirror, mirror on the wall: Building a new PHP reflection library (DPC 2016)Mirror, mirror on the wall: Building a new PHP reflection library (DPC 2016)
Mirror, mirror on the wall: Building a new PHP reflection library (DPC 2016)
 

Andere mochten auch

Deploying an application with Chef and Docker
Deploying an application with Chef and DockerDeploying an application with Chef and Docker
Deploying an application with Chef and DockerDaniel Ku
 
Google Analytics
Google AnalyticsGoogle Analytics
Google AnalyticsDaniel Ku
 
MeaNstack on Docker
MeaNstack on DockerMeaNstack on Docker
MeaNstack on DockerDaniel Ku
 
Getting Started with Redis
Getting Started with RedisGetting Started with Redis
Getting Started with RedisDaniel Ku
 
Indices APIs - Elasticsearch Reference
Indices APIs - Elasticsearch ReferenceIndices APIs - Elasticsearch Reference
Indices APIs - Elasticsearch ReferenceDaniel Ku
 
Promise and Bluebird
Promise and BluebirdPromise and Bluebird
Promise and BluebirdDaniel Ku
 

Andere mochten auch (7)

Deploying an application with Chef and Docker
Deploying an application with Chef and DockerDeploying an application with Chef and Docker
Deploying an application with Chef and Docker
 
Google Analytics
Google AnalyticsGoogle Analytics
Google Analytics
 
MeaNstack on Docker
MeaNstack on DockerMeaNstack on Docker
MeaNstack on Docker
 
Getting Started with Redis
Getting Started with RedisGetting Started with Redis
Getting Started with Redis
 
Indices APIs - Elasticsearch Reference
Indices APIs - Elasticsearch ReferenceIndices APIs - Elasticsearch Reference
Indices APIs - Elasticsearch Reference
 
Utilizing Bluebird Promises
Utilizing Bluebird PromisesUtilizing Bluebird Promises
Utilizing Bluebird Promises
 
Promise and Bluebird
Promise and BluebirdPromise and Bluebird
Promise and Bluebird
 

Ähnlich wie Object-oriented Javascript

Intro to Advanced JavaScript
Intro to Advanced JavaScriptIntro to Advanced JavaScript
Intro to Advanced JavaScriptryanstout
 
Web Optimization Summit: Coding for Performance
Web Optimization Summit: Coding for PerformanceWeb Optimization Summit: Coding for Performance
Web Optimization Summit: Coding for Performancejohndaviddalton
 
JavaScript for PHP developers
JavaScript for PHP developersJavaScript for PHP developers
JavaScript for PHP developersStoyan Stefanov
 
04 Advanced Javascript
04 Advanced Javascript04 Advanced Javascript
04 Advanced Javascriptcrgwbr
 
jQuery Data Manipulate API - A source code dissecting journey
jQuery Data Manipulate API - A source code dissecting journeyjQuery Data Manipulate API - A source code dissecting journey
jQuery Data Manipulate API - A source code dissecting journeyHuiyi Yan
 
JavaScript - Like a Box of Chocolates
JavaScript - Like a Box of ChocolatesJavaScript - Like a Box of Chocolates
JavaScript - Like a Box of ChocolatesRobert Nyman
 
Introduction to ECMAScript 2015
Introduction to ECMAScript 2015Introduction to ECMAScript 2015
Introduction to ECMAScript 2015Tomasz Dziuda
 
Beginning Object-Oriented JavaScript
Beginning Object-Oriented JavaScriptBeginning Object-Oriented JavaScript
Beginning Object-Oriented JavaScriptStoyan Stefanov
 
Object oriented javascript
Object oriented javascriptObject oriented javascript
Object oriented javascriptShah Jalal
 
JSConf: All You Can Leet
JSConf: All You Can LeetJSConf: All You Can Leet
JSConf: All You Can Leetjohndaviddalton
 
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 & AndroidJordi Gerona
 
JS Level Up: Prototypes
JS Level Up: PrototypesJS Level Up: Prototypes
JS Level Up: PrototypesVernon Kesner
 
TDC 2014 - JavaScript de qualidade: hoje, amanhã e sempre!
TDC 2014 - JavaScript de qualidade: hoje, amanhã e sempre!TDC 2014 - JavaScript de qualidade: hoje, amanhã e sempre!
TDC 2014 - JavaScript de qualidade: hoje, amanhã e sempre!Guilherme Carreiro
 
Stop Making Excuses and Start Testing Your JavaScript
Stop Making Excuses and Start Testing Your JavaScriptStop Making Excuses and Start Testing Your JavaScript
Stop Making Excuses and Start Testing Your JavaScriptRyan Anklam
 

Ähnlich wie Object-oriented Javascript (20)

Intro to Advanced JavaScript
Intro to Advanced JavaScriptIntro to Advanced JavaScript
Intro to Advanced JavaScript
 
Everyday's JS
Everyday's JSEveryday's JS
Everyday's JS
 
Web Optimization Summit: Coding for Performance
Web Optimization Summit: Coding for PerformanceWeb Optimization Summit: Coding for Performance
Web Optimization Summit: Coding for Performance
 
JavaScript for PHP developers
JavaScript for PHP developersJavaScript for PHP developers
JavaScript for PHP developers
 
04 Advanced Javascript
04 Advanced Javascript04 Advanced Javascript
04 Advanced Javascript
 
jQuery Data Manipulate API - A source code dissecting journey
jQuery Data Manipulate API - A source code dissecting journeyjQuery Data Manipulate API - A source code dissecting journey
jQuery Data Manipulate API - A source code dissecting journey
 
JavaScript - Like a Box of Chocolates
JavaScript - Like a Box of ChocolatesJavaScript - Like a Box of Chocolates
JavaScript - Like a Box of Chocolates
 
Say It With Javascript
Say It With JavascriptSay It With Javascript
Say It With Javascript
 
Introduction to ECMAScript 2015
Introduction to ECMAScript 2015Introduction to ECMAScript 2015
Introduction to ECMAScript 2015
 
Introduccion a Jasmin
Introduccion a JasminIntroduccion a Jasmin
Introduccion a Jasmin
 
Beginning Object-Oriented JavaScript
Beginning Object-Oriented JavaScriptBeginning Object-Oriented JavaScript
Beginning Object-Oriented JavaScript
 
Object oriented javascript
Object oriented javascriptObject oriented javascript
Object oriented javascript
 
JSConf: All You Can Leet
JSConf: All You Can LeetJSConf: All You Can Leet
JSConf: All You Can Leet
 
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
 
JS Level Up: Prototypes
JS Level Up: PrototypesJS Level Up: Prototypes
JS Level Up: Prototypes
 
TDC 2014 - JavaScript de qualidade: hoje, amanhã e sempre!
TDC 2014 - JavaScript de qualidade: hoje, amanhã e sempre!TDC 2014 - JavaScript de qualidade: hoje, amanhã e sempre!
TDC 2014 - JavaScript de qualidade: hoje, amanhã e sempre!
 
JavaScript patterns
JavaScript patternsJavaScript patterns
JavaScript patterns
 
Stop Making Excuses and Start Testing Your JavaScript
Stop Making Excuses and Start Testing Your JavaScriptStop Making Excuses and Start Testing Your JavaScript
Stop Making Excuses and Start Testing Your JavaScript
 
Javascript tid-bits
Javascript tid-bitsJavascript tid-bits
Javascript tid-bits
 
ECMAScript 5: Новое в JavaScript
ECMAScript 5: Новое в JavaScriptECMAScript 5: Новое в JavaScript
ECMAScript 5: Новое в JavaScript
 

Kürzlich hochgeladen

Scaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationScaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationRadu Cotescu
 
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time AutomationFrom Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time AutomationSafe Software
 
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost SavingRepurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost SavingEdi Saputra
 
MINDCTI Revenue Release Quarter One 2024
MINDCTI Revenue Release Quarter One 2024MINDCTI Revenue Release Quarter One 2024
MINDCTI Revenue Release Quarter One 2024MIND CTI
 
2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...Martijn de Jong
 
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 2024The Digital Insurer
 
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot TakeoffStrategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoffsammart93
 
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...apidays
 
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...apidays
 
Top 10 Most Downloaded Games on Play Store in 2024
Top 10 Most Downloaded Games on Play Store in 2024Top 10 Most Downloaded Games on Play Store in 2024
Top 10 Most Downloaded Games on Play Store in 2024SynarionITSolutions
 
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...Drew Madelung
 
Manulife - Insurer Innovation Award 2024
Manulife - Insurer Innovation Award 2024Manulife - Insurer Innovation Award 2024
Manulife - Insurer Innovation Award 2024The Digital Insurer
 
Apidays New York 2024 - The value of a flexible API Management solution for O...
Apidays New York 2024 - The value of a flexible API Management solution for O...Apidays New York 2024 - The value of a flexible API Management solution for O...
Apidays New York 2024 - The value of a flexible API Management solution for O...apidays
 
A Year of the Servo Reboot: Where Are We Now?
A Year of the Servo Reboot: Where Are We Now?A Year of the Servo Reboot: Where Are We Now?
A Year of the Servo Reboot: Where Are We Now?Igalia
 
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)wesley chun
 
Exploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone ProcessorsExploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone Processorsdebabhi2
 
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 2024Rafal Los
 
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.pdfUK Journal
 
Polkadot JAM Slides - Token2049 - By Dr. Gavin Wood
Polkadot JAM Slides - Token2049 - By Dr. Gavin WoodPolkadot JAM Slides - Token2049 - By Dr. Gavin Wood
Polkadot JAM Slides - Token2049 - By Dr. Gavin WoodJuan lago vázquez
 
Why Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire businessWhy Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire businesspanagenda
 

Kürzlich hochgeladen (20)

Scaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationScaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organization
 
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time AutomationFrom Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
 
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost SavingRepurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
 
MINDCTI Revenue Release Quarter One 2024
MINDCTI Revenue Release Quarter One 2024MINDCTI Revenue Release Quarter One 2024
MINDCTI Revenue Release Quarter One 2024
 
2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...
 
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
 
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot TakeoffStrategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
 
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...
 
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
 
Top 10 Most Downloaded Games on Play Store in 2024
Top 10 Most Downloaded Games on Play Store in 2024Top 10 Most Downloaded Games on Play Store in 2024
Top 10 Most Downloaded Games on Play Store in 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...
 
Manulife - Insurer Innovation Award 2024
Manulife - Insurer Innovation Award 2024Manulife - Insurer Innovation Award 2024
Manulife - Insurer Innovation Award 2024
 
Apidays New York 2024 - The value of a flexible API Management solution for O...
Apidays New York 2024 - The value of a flexible API Management solution for O...Apidays New York 2024 - The value of a flexible API Management solution for O...
Apidays New York 2024 - The value of a flexible API Management solution for O...
 
A Year of the Servo Reboot: Where Are We Now?
A Year of the Servo Reboot: Where Are We Now?A Year of the Servo Reboot: Where Are We Now?
A Year of the Servo Reboot: Where Are We Now?
 
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)
 
Exploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone ProcessorsExploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone Processors
 
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
 
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
 
Polkadot JAM Slides - Token2049 - By Dr. Gavin Wood
Polkadot JAM Slides - Token2049 - By Dr. Gavin WoodPolkadot JAM Slides - Token2049 - By Dr. Gavin Wood
Polkadot JAM Slides - Token2049 - By Dr. Gavin Wood
 
Why Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire businessWhy Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire business
 

Object-oriented Javascript

  • 1. Object-oriented Javascript Daniel Ku (http://kjunine.net/)
  • 3. “Is Everything in JavaScript an object?”
  • 5. Primitives » string » number » boolean » undefined » null Everything else is object.
  • 6. “WHAT? Strings have properties and methods!”
  • 7. var p = 'hello'; p.test = 'test'; console.log(p.test); // ? var o = new String('hello'); o.test = 'test'; console.log(o.test); // ?
  • 8. var p = 'hello'; p.test = 'test'; console.log(p.test); // undefined var o = new String('hello'); o.test = 'test'; console.log(o.test); // test
  • 9. typeof 'hello'; // string typeof new String('hello'); // object typeof 10 // number typeof new Number(10); // object typeof false; // boolean typeof new Boolean(true); // object typeof undefined; // undefined typeof null; // object ???
  • 10. HOW to create an object?
  • 12. var createPerson = function(firstName, lastName) { return { firstName: firstName, lastName: lastName, sayHi: function() { return 'Hi there'; } }; }; var john = createPerson('John', 'Doe'); var jane = createPerson('Jane', 'Doe');
  • 13. IT WORKS! BUT, BAD PRACTICE!
  • 15. this is » window in global context » the object in an object
  • 16. var name = 'Jane'; var greet = function() { return 'My name is ' + this.name; } var person = { name: 'John', greet: greet }; greet(); // ? person.greet(); // ?
  • 17. var name = 'Jane'; var greet = function() { return 'My name is ' + this.name; } var person = { name: 'John', greet: greet }; greet(); // My name is Jane person.greet(); // My name is John
  • 18. var requestAsync = function(url, callback) { var data = 10; callback(data); }; var requestor = { value: 20, process: function(data) { var sum = this.value + data; console.log(sum); }, request: function() { var url = 'http://example.com'; requestAsync(url, this.process); } }; requestor.request(); // ?
  • 19. var requestAsync = function(url, callback) { var data = 10; callback(data); }; var requestor = { value: 20, process: function(data) { var sum = this.value + data; console.log(sum); }, request: function() { var url = 'http://example.com'; requestAsync(url, this.process); } }; requestor.request(); // NaN
  • 21. var requestAsync = function(url, callback) { var data = 10; callback(data); }; var requestor = { value: 20, process: function(data) { var sum = this.value + data; console.log(sum); }, request: function() { var url = 'http://example.com'; requestAsync(url, this.process.bind(this)); } }; requestor.request(); // 30
  • 23. var Person = function(firstName, lastName) { this.firstName = firstName; this.lastName = lastName; this.sayHi = function() { return 'Hi~'; }; }; var person = new Person('John', 'Doe');
  • 24. Also, BAD PRACTICE! Do like next.
  • 25. var Person = function(firstName, lastName) { this.firstName = firstName; this.lastName = lastName; }; Person.prototype.sayHi = function() { return 'Hi~'; }; var person = new Person('John', 'Doe');
  • 27.
  • 28.
  • 30. person.constructor === Person; // true person.__proto__ === Person.prototype; // true Object.getPrototypeOf(person) === Person.prototype; // true
  • 31. person.hasOwnProperty('firstName'); // true person.hasOwnProperty('lastName'); // true person.hasOwnProperty('sayHi'); // false person.constructor .prototype .hasOwnProperty('sayHi'); // true
  • 32. Properties and Property Descriptors
  • 33. var person = {}; Object.defineProperty(person, 'firstName', { // descriptor object (data descriptor) value: 'John', writable: true }); Object.defineProperty(person, 'lastName', { value: 'Doe', writable: false }); person.firstName; // 'John' person.lastName; // 'Doe'
  • 34. person.firstName = 'Jane'; person.firstName; // 'Jane' person.lastName = 'Dummy'; person.lastName; // 'Doe'
  • 35. var person = {}; Object.defineProperties(person, { firstName: { value: 'John', writable: true }, lastName: { value: 'Doe', writable: true }, fullName: { // accessor descriptor get: function() { return this.firstName + ' ' + this.lastName; }, set: function(value) { var splits = value.split(' '); this.firstName = splits[0]; this.lastName = splits[1]; } } });
  • 36. person.fullName; // 'John Doe' person.fullName = 'Jane Eyre' person.firstName; // 'Jane' person.lastName; // 'Eyre' person.fullName; // 'Jane Eyre'
  • 37. var person = {}; Object.defineProperty(person, 'firstName', { value: 'John', enumerable: true }); Object.defineProperty(person, 'lastName', { value: 'Doe', enumerable: false }); for (var key in person) { console.log(key, '=>' , person[key]); } // 'firstName => John'
  • 38. Object.defineProperty » Property Descriptors » Data Descriptors » Accessor Descriptors » reference » es5-shim
  • 39. Common Keys of Descriptors » configurable (default: false) » enumerable (default: false)
  • 40. Keys of Data Descriptors » value (default: undefined) » writable (default: false)
  • 41. Keys of Accessor Descriptors » get (default: undefined) » set (default: undefined)
  • 42. Constructors and the Prototype REVISITED
  • 43. var Person = function(firstName, lastName) { Object.defineProperty(this, 'firstName', { value: firstName, writable: true, enumerable: true }); Object.defineProperty(this, 'lastName', { value: lastName, writable: true, enumerable: true }); };
  • 44. Object.defineProperties(Person.prototype, { sayHi: { value: function() { return 'Hi there'; } }, fullName: { get: function() { return this.firstName + ' ' + this.lastName; }, enumerable: true } }); var person = new Person('John', 'Doe');
  • 45. HOW to do inheritance?
  • 48. var person = { firstName: 'John', lastName: 'Doe' }; var employee = Object.create(person); Object.getPrototypeOf(employee) === person; // true
  • 50. var Person = function(firstName, lastName) { this.firstName = firstName; this.lastName = lastName; }; Person.prototype.sayHi = function() { return 'Hi~'; }; var person = new Person('John', 'Doe'); Object.getOwnPropertyDescriptor(Person.prototype, 'sayHi'); // {value: function, writable: true, enumerable: true, configurable: true} Object.getOwnPropertyDescriptor(person, 'firstName'); // {value: "John", writable: true, enumerable: true, configurable: true}
  • 52. var Person = function(firstName, lastName) { Object.defineProperties(this, { firstName: { value: firstName, writable: true, enumerable: true }, lastName: { value: lastName, writable: true, enumerable: true } }); }; Object.defineProperties(Person.prototype, { sayHi: { value: function() { return 'Hi there'; } }, fullName: { get: function() { return this.firstName + ' ' + this.lastName; }, enumerable: true } });
  • 53. var Employee = function(firstName, lastName, position) { Person.call(this, firstName, lastName); Object.defineProperties(this, { position: { value: position, writable: true, enumerable: true } }); };
  • 54. Employee.prototype = Object.create(Person.prototype, { sayHi: { value: function() { return Person.prototype.sayHi.call(this) + ' and here'; } }, fullName: { get: function() { var descriptor = Object.getOwnPropertyDescriptor(Person.prototype, 'fullName'); return descriptor.get.call(this) + ' ' + this.position; }, enumerable: true }, constructor: { value: Employee } });
  • 55. var employee = new Employee('John', 'Doe', 'Manager'); for (var key in employee) { console.log(key, '=>' , employee[key]); } // 'firstName => John' // 'lastName => Doe' // 'position => Manager' // 'fullName => John Doe Manager'
  • 57.
  • 58. Object.getPrototypeOf(employee) === Employee.prototype; // true employee.__proto__ === Employee.prototype; // true employee.__proto__.__proto__ === Person.prototype; // true employee.__proto__.__proto__.__proto__ === Object.prototype; // true employee.__proto__.__proto__.__proto__.__proto__ === null; // true
  • 59. References » Object-Oriented JavaScript on Tuts+ » Inheritance revisited on MDN » ECMA-262-5 in detail by Dmitry Soshnikov