SlideShare ist ein Scribd-Unternehmen logo
1 von 64
Downloaden Sie, um offline zu lesen
this
othree@JSDC
this
• ‘the object’ it belongs in OOP
C++
class Box {
public:
Box(double l=2.0, double b=2.0, double h=2.0) {
this->length = l;
this->breadth = b;
this->height = h;
}
double Volume() {
return length * breadth * height;
}
int compare(Box box) {
return this->Volume() > box.Volume();
}
private:
double length;
double breadth;
double height;
};
Continued..
int main(void)
{
Box Box1(3.3, 1.2, 1.5);
Box Box2(8.5, 6.0, 2.0);
cout << Box1.Volume() << endl; // 3.3*1.2*1.5 = 5.94
cout << Box2.Volume() << endl; // 8.5*6.0*2.0 = 102
return 0;
}
this
• Context in JavaScript
• Can mean the object also
JavaScript
var Box = function Box (l, b, h) {
this.length = l;
this.breadth = b;
this.height = h;
};
Box.prototype.Volume = function () {
return this.length * this.breadth * this.height;
};
Box.prototype.compare = function (box) {
return this.Volume() > box.Volume();
};
this in Function
• Context
• Depends on how you call the function
3 Way to Call Function
var big = function () {/*...*/};
var foo = {
small: function () {/*...*/}
};
big(); // 1. this: window object
foo.small(); // 2. this: foo
var small = foo.small;
small();
3 Way to Call Function
var big = function () {/*...*/};
var foo = {
small: function () {/*...*/}
};
big(); // 1. this: window object
foo.small(); // 2. this: foo
var small = foo.small;
small(); // 3. this: window object
Borrowing Method
var foo = {
small: function () {
this;
}
};
var bar = {};
foo.small(); // this: foo
bar.borrowedSmall = foo.small;
bar.borrowedSmall(); // this: bar
this in Global Scope
• Root object
Root Object
• `window` in browsers
• Root object in other environment
to Support Both
(function () {
root = this;
//blah....
}());
Strict Mode
• No more global context
Don’t Forget `new`
function Foobar() {
"use strict";
this.a = 'foo';
this.b = 'bar';
}
var foobar1 = Foobar();
// Cannot set property 'a' of undefined
var foobar2 = new Foobar();
// this: new empty object
One More Way to Call
Function
apply/call
var foo = {};
function foobar(v1, v2) {
this.bar1 = v1;
this.bar2 = v2;
}
foobar.call(foo, v1, v2); // this: foo
foobar.apply(foo, [v1, v2]); // this: foo
bind
var foo = {};
var otherFoo = {};
function setBar(v1, v2) {
this.bar1 = v1;
this.bar2 = v2;
}
var fooSetBar = setBar.bind(foo);
fooSetBar(1, 2); // this: foo
otherFoo.foobar = fooSetBar;
otherFoo.foobar(3, 4); // this: foo
ProtectYour Method
• Bind context and function together
$.proxy/_.bind
• Use apply to implement bind
Implement Bind
var bind = function (func, context) {
return function () {
func.apply(context, arguments);
};
};
Solve Event Handler
• Use apply to assign context
• JavaScript Libraries did it for you
this in Event Handler
// W3C Dom
aElement.addEventListener('click', function () {
this; // aElement
}, false);
// old IE
aElement.attachEvent('onclick', function () {
this; // window
});
Callback Function
function Foobar (input) {
this.prefix = input;
}
Foobar.prototype.echo = function (result) {
return this.prefix + result;
};
fb = new Foobar();
$.get('/info', function (result) {
fb.echo(result);
});
Reduce One Stack
function Foobar (input) {
this.prefix = input;
}
Foobar.prototype.echo = function (result) {
return this.prefix + result;
};
fb = new Foobar();
$.get('/info', fb.echo); // this.prefix is 'undefined'
Use bind
function Foobar (input) {
this.prefix = input;
this.echo = this.echo.bind(this); // Protect method
}
Foobar.prototype.echo = function (result) {
return this.prefix + result;
};
fb = new Foobar();
$.get('/info', fb.echo);
Cons
• Performance is bad
• Old browser don’t support
Performance
http://jsperf.com/bind-vs-closure-setup/10
Pros
• Clearer code
Use _.bind
function Foobar (input) {
this.prefix = input;
this.echo = _.bind(this.echo, this);
// function, context
}
function Foobar (input) {
this.prefix = input;
_.bindAll(this);
// context
}
http://underscorejs.org/#bind
Use $.proxy
function Foobar (input) {
this.prefix = input;
this.echo = $.proxy(this.echo, this);
// function, context
}
function Foobar (input) {
this.prefix = input;
this.echo = $.proxy(this, 'echo');
// context, method name
}
http://api.jquery.com/jQuery.proxy/
Bind by Need
fb = new Foobar();
$.get('/info', $.proxy(fb, 'echo'));
$.get('/info', $.proxy(fb.echo, fb));
$.get('/info', $.bind(fb.echo, fb));
http://www.flickr.com/photos/othree/8544069132/
Avoid Using this
Closure
var isIE = true;
function foobar() {
if (!isIE) {
// access isIE is possible because of closure
return;
}
// blah...
};
that/self
function Foobar(input) {
var that = this; // that or self
this.prefix = input;
this.echo = function (result) {
return that.prefix + result;
// that is accessible because of closure
};
}
fb = new Foobar('res: ');
$.get('/info', fb.echo);
CoffeeScript Fat Arrow
Foobar = (input) ->
@prefix = input
@echo = (result) => @prefix + result
fb = new Foobar('res: ')
$.get('/info', fb.echo)
CoffeeScript Fat Arrow
Foobar = (input) ->
@prefix = input
@echo = (result) => @prefix + result
fb = new Foobar('res: ')
$.get('/info', fb.echo)
Compile to JS
var Foobar, fb;
Foobar = function(input) {
var _this = this;
this.prefix = input;
return this.echo = function(result) {
return _this.prefix + result;
};
};
fb = new Foobar('res: ');
$.get('/info', fb.echo);
Compile to JS
var Foobar, fb;
Foobar = function(input) {
var _this = this;
this.prefix = input;
return this.echo = function(result) {
return _this.prefix + result;
};
};
fb = new Foobar('res: ');
$.get('/info', fb.echo);
Compile to JS
var Foobar, fb;
Foobar = function(input) {
var _this = this;
this.prefix = input;
return this.echo = function(result) {
return _this.prefix + result;
};
};
fb = new Foobar('res: ');
$.get('/info', fb.echo);
LiveScript use ~>
Pros
• No more this issue, context free
• Reduce one call stack
• No call/apply, no impact on performance
• Encapsulation
Cons
• Can’t use this tip on normal constructor
How about AMD
• Define modules can return constructor,
function, array, primitive data
• Define a singleton module on most cases
• Always have data on module
AMD Singleton Module
define('foobar', function () {
return {
init: function (prefix) {
this.prefix = prefix;
}
echo: function (input) {
return this.prefix + input;
}
};
});
Cons
• Function can be borrowed
• Not doing on right `this` you expect
Avoid Use this
define('foobar', function () {
var self = {};
return {
init: function (prefix) {
self.prefix = prefix;
}
echo: function (input) {
return self.prefix + input;
}
};
});
Constructors?
• Use bind to protect methods if necessary
Constructor Without
this
function Person(birth, gender) {
var person = {
birth: (birth || '1970/01/01'),
gender: (gender || 'M')
};
return {
getBirth: function () {
return person.birth;
},
getGender: function () {
return person.gender;
}
};
}
to new or not to new
var p1 = Person('2013/01/02');
p1.getBirth(); // "2013/01/02"
var p2 = new Person('2000/01/02', 'F');
p2.getBirth(); // "2000/01/02"
p1.getBirth(); // "2013/01/02"
Cons
• No prototype inheritance
• More memory usage for methods
Backbone Model
define(function (require) {
return Backbone.Model.extend(
initialize: function (attrs) {
return _.bindAll(this);
},
toITEM: function () {
return this.toJSON();
},
toConfig: function () {
return {
name: this.get('name'),
package_name: this.get('package_name')
};
}
);
});
Who Use this Tip
• jQuery.Deferred
• jQuery.Callbacks
Deferred Chaining
var firstDfd = $.Deferred(),
secondDfd = $.Deferred(),
thirdDfd = $.Deferred();
firstDfd.done(secondDfd.resolve);
secondDfd.done(thirdDfd.resolve);
firstDfd.resolve(); // All Deferred object resolved here
Callbacks
https://github.com/jquery/jquery/blob/master/src/deferred.js
// promise[ done | fail | progress ] = list.add
promise[ tuple[1] ] = list.add;
// skip...
// deferred[ resolve | reject | notify ]
deferred[ tuple[0] ] = function() {
deferred[ tuple[0] + "With" ]
(this === deferred ? promise : this, arguments);
return this;
};
deferred[ tuple[0] + "With" ] = list.fireWith;
Callbacks
https://github.com/jquery/jquery/blob/master/src/deferred.js
// promise[ done | fail | progress ] = list.add
promise[ tuple[1] ] = list.add;
// skip...
// deferred[ resolve | reject | notify ]
deferred[ tuple[0] ] = function() {
deferred[ tuple[0] + "With" ]
(this === deferred ? promise : this, arguments);
return this;
};
deferred[ tuple[0] + "With" ] = list.fireWith;
Actually Are
promise['done'] = resolveCallbacks.add;
promise['fail'] = rejectCallbacks.add;
promise['progress'] = notifyCallbacks.add;
// skip...
deferred["resolveWith"] = resolveCallbacks.fireWith;
deferred["rejectWith"] = rejectCallbacks.fireWith;
deferred["notifyWith"] = notifyCallbacks.fireWith;
Summary
• Understand `this`
• Understand how not to use `this`
• Use `this` carefully if necessary
Trade-Off
• ‘Not use this’ requires more memory on
methods denition and not easy to
inheritance object
• Benefit is you can write more clear, simple
code
References
https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Operators/this
Questions?
http://www.flickr.com/photos/roman/5610736/

Weitere ähnliche Inhalte

Was ist angesagt?

The Beauty Of Java Script V5a
The Beauty Of Java Script V5aThe Beauty Of Java Script V5a
The Beauty Of Java Script V5a
rajivmordani
 
HelsinkiJS meet-up. Dmitry Soshnikov - ECMAScript 6
HelsinkiJS meet-up. Dmitry Soshnikov - ECMAScript 6HelsinkiJS meet-up. Dmitry Soshnikov - ECMAScript 6
HelsinkiJS meet-up. Dmitry Soshnikov - ECMAScript 6
Dmitry Soshnikov
 
Mulberry: A Mobile App Development Toolkit
Mulberry: A Mobile App Development ToolkitMulberry: A Mobile App Development Toolkit
Mulberry: A Mobile App Development Toolkit
Rebecca Murphey
 

Was ist angesagt? (20)

Cycle.js: Functional and Reactive
Cycle.js: Functional and ReactiveCycle.js: Functional and Reactive
Cycle.js: Functional and Reactive
 
Writing Clean Code in Swift
Writing Clean Code in SwiftWriting Clean Code in Swift
Writing Clean Code in Swift
 
JavaScript ES6
JavaScript ES6JavaScript ES6
JavaScript ES6
 
Say It With Javascript
Say It With JavascriptSay It With Javascript
Say It With Javascript
 
ES6 in Real Life
ES6 in Real LifeES6 in Real Life
ES6 in Real Life
 
ES6 PPT FOR 2016
ES6 PPT FOR 2016ES6 PPT FOR 2016
ES6 PPT FOR 2016
 
The Beauty Of Java Script V5a
The Beauty Of Java Script V5aThe Beauty Of Java Script V5a
The Beauty Of Java Script V5a
 
HelsinkiJS meet-up. Dmitry Soshnikov - ECMAScript 6
HelsinkiJS meet-up. Dmitry Soshnikov - ECMAScript 6HelsinkiJS meet-up. Dmitry Soshnikov - ECMAScript 6
HelsinkiJS meet-up. Dmitry Soshnikov - ECMAScript 6
 
The Beauty of Java Script
The Beauty of Java ScriptThe Beauty of Java Script
The Beauty of Java Script
 
EcmaScript 6 - The future is here
EcmaScript 6 - The future is hereEcmaScript 6 - The future is here
EcmaScript 6 - The future is here
 
Js hacks
Js hacksJs hacks
Js hacks
 
Your JavaScript Library
Your JavaScript LibraryYour JavaScript Library
Your JavaScript Library
 
A New Baseline for Front-End Devs
A New Baseline for Front-End DevsA New Baseline for Front-End Devs
A New Baseline for Front-End Devs
 
ES6: The Awesome Parts
ES6: The Awesome PartsES6: The Awesome Parts
ES6: The Awesome Parts
 
Mulberry: A Mobile App Development Toolkit
Mulberry: A Mobile App Development ToolkitMulberry: A Mobile App Development Toolkit
Mulberry: A Mobile App Development Toolkit
 
Fact, Fiction, and FP
Fact, Fiction, and FPFact, Fiction, and FP
Fact, Fiction, and FP
 
Lenses
LensesLenses
Lenses
 
jQuery Namespace Pattern
jQuery Namespace PatternjQuery Namespace Pattern
jQuery Namespace Pattern
 
PHP 5.3 and Lithium: the most rad php framework
PHP 5.3 and Lithium: the most rad php frameworkPHP 5.3 and Lithium: the most rad php framework
PHP 5.3 and Lithium: the most rad php framework
 
ES6 is Nigh
ES6 is NighES6 is Nigh
ES6 is Nigh
 

Andere mochten auch

Functions and Objects in JavaScript
Functions and Objects in JavaScript Functions and Objects in JavaScript
Functions and Objects in JavaScript
Dhananjay Kumar
 
Javascript by geetanjali
Javascript by geetanjaliJavascript by geetanjali
Javascript by geetanjali
Geetanjali Bhosale
 
Good Parts of JavaScript Douglas Crockford
Good Parts of JavaScript Douglas CrockfordGood Parts of JavaScript Douglas Crockford
Good Parts of JavaScript Douglas Crockford
rajivmordani
 
Basics of computer science
Basics of computer scienceBasics of computer science
Basics of computer science
Paul Schmidt
 

Andere mochten auch (20)

Functions and Objects in JavaScript
Functions and Objects in JavaScript Functions and Objects in JavaScript
Functions and Objects in JavaScript
 
Bringbestoinyou
BringbestoinyouBringbestoinyou
Bringbestoinyou
 
Object Oriented Javascript
Object Oriented JavascriptObject Oriented Javascript
Object Oriented Javascript
 
Javascript - Array - Writing
Javascript - Array - WritingJavascript - Array - Writing
Javascript - Array - Writing
 
javascript objects
javascript objectsjavascript objects
javascript objects
 
Javascript good parts - for novice programmers
Javascript good parts - for novice programmersJavascript good parts - for novice programmers
Javascript good parts - for novice programmers
 
Strings
StringsStrings
Strings
 
Datatype
DatatypeDatatype
Datatype
 
Javascript by geetanjali
Javascript by geetanjaliJavascript by geetanjali
Javascript by geetanjali
 
Tree and Binary Search tree
Tree and Binary Search treeTree and Binary Search tree
Tree and Binary Search tree
 
Javascript - Array - Creating Array
Javascript - Array - Creating ArrayJavascript - Array - Creating Array
Javascript - Array - Creating Array
 
Learn REST in 18 Slides
Learn REST in 18 SlidesLearn REST in 18 Slides
Learn REST in 18 Slides
 
The JavaScript You Wished You Knew
The JavaScript You Wished You KnewThe JavaScript You Wished You Knew
The JavaScript You Wished You Knew
 
Good Parts of JavaScript Douglas Crockford
Good Parts of JavaScript Douglas CrockfordGood Parts of JavaScript Douglas Crockford
Good Parts of JavaScript Douglas Crockford
 
JavaScript - From Birth To Closure
JavaScript - From Birth To ClosureJavaScript - From Birth To Closure
JavaScript - From Birth To Closure
 
Structure of url, uniform resource locator
Structure of url, uniform resource locatorStructure of url, uniform resource locator
Structure of url, uniform resource locator
 
JavaScript Functions
JavaScript FunctionsJavaScript Functions
JavaScript Functions
 
Javascript para principiantes -IntroducciĂłn
Javascript para principiantes -IntroducciĂłnJavascript para principiantes -IntroducciĂłn
Javascript para principiantes -IntroducciĂłn
 
Introduction to JSON
Introduction to JSONIntroduction to JSON
Introduction to JSON
 
Basics of computer science
Basics of computer scienceBasics of computer science
Basics of computer science
 

Ähnlich wie this

Jsphp 110312161301-phpapp02
Jsphp 110312161301-phpapp02Jsphp 110312161301-phpapp02
Jsphp 110312161301-phpapp02
Seri Moth
 
JavaScript for PHP developers
JavaScript for PHP developersJavaScript for PHP developers
JavaScript for PHP developers
Stoyan Stefanov
 
Orlando BarCamp Why Javascript Doesn't Suck
Orlando BarCamp Why Javascript Doesn't SuckOrlando BarCamp Why Javascript Doesn't Suck
Orlando BarCamp Why Javascript Doesn't Suck
erockendude
 
Introducing PHP Latest Updates
Introducing PHP Latest UpdatesIntroducing PHP Latest Updates
Introducing PHP Latest Updates
Iftekhar Eather
 

Ähnlich wie this (20)

Jsphp 110312161301-phpapp02
Jsphp 110312161301-phpapp02Jsphp 110312161301-phpapp02
Jsphp 110312161301-phpapp02
 
JavaScript for PHP developers
JavaScript for PHP developersJavaScript for PHP developers
JavaScript for PHP developers
 
ECMAScript 6
ECMAScript 6ECMAScript 6
ECMAScript 6
 
Javascript tid-bits
Javascript tid-bitsJavascript tid-bits
Javascript tid-bits
 
Orlando BarCamp Why Javascript Doesn't Suck
Orlando BarCamp Why Javascript Doesn't SuckOrlando BarCamp Why Javascript Doesn't Suck
Orlando BarCamp Why Javascript Doesn't Suck
 
EcmaScript 6
EcmaScript 6 EcmaScript 6
EcmaScript 6
 
Workshop 10: ECMAScript 6
Workshop 10: ECMAScript 6Workshop 10: ECMAScript 6
Workshop 10: ECMAScript 6
 
Introduction to ECMAScript 2015
Introduction to ECMAScript 2015Introduction to ECMAScript 2015
Introduction to ECMAScript 2015
 
Javascript this keyword
Javascript this keywordJavascript this keyword
Javascript this keyword
 
Object Oriented JavaScript
Object Oriented JavaScriptObject Oriented JavaScript
Object Oriented JavaScript
 
Functional Programming in PHP
Functional Programming in PHPFunctional Programming in PHP
Functional Programming in PHP
 
Introducing PHP Latest Updates
Introducing PHP Latest UpdatesIntroducing PHP Latest Updates
Introducing PHP Latest Updates
 
ES6: Features + Rails
ES6: Features + RailsES6: Features + Rails
ES6: Features + Rails
 
Ian 20150116 java script oop
Ian 20150116 java script oopIan 20150116 java script oop
Ian 20150116 java script oop
 
JSConf: All You Can Leet
JSConf: All You Can LeetJSConf: All You Can Leet
JSConf: All You Can Leet
 
Advanced JavaScript
Advanced JavaScript Advanced JavaScript
Advanced JavaScript
 
JavaScript - Like a Box of Chocolates
JavaScript - Like a Box of ChocolatesJavaScript - Like a Box of Chocolates
JavaScript - Like a Box of Chocolates
 
Web Optimization Summit: Coding for Performance
Web Optimization Summit: Coding for PerformanceWeb Optimization Summit: Coding for Performance
Web Optimization Summit: Coding for Performance
 
Txjs
TxjsTxjs
Txjs
 
How DRY impacts JavaScript performance // Faster JavaScript execution for the...
How DRY impacts JavaScript performance // Faster JavaScript execution for the...How DRY impacts JavaScript performance // Faster JavaScript execution for the...
How DRY impacts JavaScript performance // Faster JavaScript execution for the...
 

Mehr von 偉格 高 (12)

node ffi
node ffinode ffi
node ffi
 
ECMAScript 6
ECMAScript 6ECMAScript 6
ECMAScript 6
 
Web Component
Web ComponentWeb Component
Web Component
 
Mobile web application
Mobile web applicationMobile web application
Mobile web application
 
Web Developer Tools for ICOS 2013
Web Developer Tools for ICOS 2013Web Developer Tools for ICOS 2013
Web Developer Tools for ICOS 2013
 
Module, AMD, RequireJS
Module, AMD, RequireJSModule, AMD, RequireJS
Module, AMD, RequireJS
 
Vim Plugin Deployment
Vim Plugin DeploymentVim Plugin Deployment
Vim Plugin Deployment
 
WAI-ARIA is More Than Accessibility
WAI-ARIA is More Than AccessibilityWAI-ARIA is More Than Accessibility
WAI-ARIA is More Than Accessibility
 
WAI-ARIA
WAI-ARIAWAI-ARIA
WAI-ARIA
 
TOSSUG HTML5 讀書會 新標籤與表單
TOSSUG HTML5 讀書會 新標籤與表單TOSSUG HTML5 讀書會 新標籤與表單
TOSSUG HTML5 讀書會 新標籤與表單
 
Html5 New Features
Html5 New FeaturesHtml5 New Features
Html5 New Features
 
Base2
Base2Base2
Base2
 

KĂźrzlich hochgeladen

+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
?#DUbAI#??##{{(☎️+971_581248768%)**%*]'#abortion pills for sale in dubai@
 
Artificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and MythsArtificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and Myths
Joaquim Jorge
 

KĂźrzlich hochgeladen (20)

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
 
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
 
Data Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt RobisonData Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt Robison
 
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, AdobeApidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
 
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...
 
Manulife - Insurer Innovation Award 2024
Manulife - Insurer Innovation Award 2024Manulife - Insurer Innovation Award 2024
Manulife - Insurer Innovation Award 2024
 
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemkeProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
 
Artificial Intelligence Chap.5 : Uncertainty
Artificial Intelligence Chap.5 : UncertaintyArtificial Intelligence Chap.5 : Uncertainty
Artificial Intelligence Chap.5 : Uncertainty
 
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...
 
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
 
Boost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdfBoost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdf
 
Artificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and MythsArtificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and Myths
 
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
 
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
 
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
 
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
 
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 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, ...
 
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
 
A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)
 

this

  • 2.
  • 4. C++ class Box { public: Box(double l=2.0, double b=2.0, double h=2.0) { this->length = l; this->breadth = b; this->height = h; } double Volume() { return length * breadth * height; } int compare(Box box) { return this->Volume() > box.Volume(); } private: double length; double breadth; double height; };
  • 5. Continued.. int main(void) { Box Box1(3.3, 1.2, 1.5); Box Box2(8.5, 6.0, 2.0); cout << Box1.Volume() << endl; // 3.3*1.2*1.5 = 5.94 cout << Box2.Volume() << endl; // 8.5*6.0*2.0 = 102 return 0; }
  • 6. this • Context in JavaScript • Can mean the object also
  • 7. JavaScript var Box = function Box (l, b, h) { this.length = l; this.breadth = b; this.height = h; }; Box.prototype.Volume = function () { return this.length * this.breadth * this.height; }; Box.prototype.compare = function (box) { return this.Volume() > box.Volume(); };
  • 8. this in Function • Context • Depends on how you call the function
  • 9. 3 Way to Call Function var big = function () {/*...*/}; var foo = { small: function () {/*...*/} }; big(); // 1. this: window object foo.small(); // 2. this: foo var small = foo.small; small();
  • 10. 3 Way to Call Function var big = function () {/*...*/}; var foo = { small: function () {/*...*/} }; big(); // 1. this: window object foo.small(); // 2. this: foo var small = foo.small; small(); // 3. this: window object
  • 11. Borrowing Method var foo = { small: function () { this; } }; var bar = {}; foo.small(); // this: foo bar.borrowedSmall = foo.small; bar.borrowedSmall(); // this: bar
  • 12. this in Global Scope • Root object
  • 13. Root Object • `window` in browsers • Root object in other environment
  • 14. to Support Both (function () { root = this; //blah.... }());
  • 15. Strict Mode • No more global context
  • 16. Don’t Forget `new` function Foobar() { "use strict"; this.a = 'foo'; this.b = 'bar'; } var foobar1 = Foobar(); // Cannot set property 'a' of undefined var foobar2 = new Foobar(); // this: new empty object
  • 17. One More Way to Call Function
  • 18. apply/call var foo = {}; function foobar(v1, v2) { this.bar1 = v1; this.bar2 = v2; } foobar.call(foo, v1, v2); // this: foo foobar.apply(foo, [v1, v2]); // this: foo
  • 19. bind var foo = {}; var otherFoo = {}; function setBar(v1, v2) { this.bar1 = v1; this.bar2 = v2; } var fooSetBar = setBar.bind(foo); fooSetBar(1, 2); // this: foo otherFoo.foobar = fooSetBar; otherFoo.foobar(3, 4); // this: foo
  • 20. ProtectYour Method • Bind context and function together
  • 21. $.proxy/_.bind • Use apply to implement bind
  • 22. Implement Bind var bind = function (func, context) { return function () { func.apply(context, arguments); }; };
  • 23. Solve Event Handler • Use apply to assign context • JavaScript Libraries did it for you
  • 24. this in Event Handler // W3C Dom aElement.addEventListener('click', function () { this; // aElement }, false); // old IE aElement.attachEvent('onclick', function () { this; // window });
  • 25. Callback Function function Foobar (input) { this.prefix = input; } Foobar.prototype.echo = function (result) { return this.prefix + result; }; fb = new Foobar(); $.get('/info', function (result) { fb.echo(result); });
  • 26. Reduce One Stack function Foobar (input) { this.prefix = input; } Foobar.prototype.echo = function (result) { return this.prefix + result; }; fb = new Foobar(); $.get('/info', fb.echo); // this.prefix is 'undefined'
  • 27. Use bind function Foobar (input) { this.prefix = input; this.echo = this.echo.bind(this); // Protect method } Foobar.prototype.echo = function (result) { return this.prefix + result; }; fb = new Foobar(); $.get('/info', fb.echo);
  • 28. Cons • Performance is bad • Old browser don’t support
  • 31. Use _.bind function Foobar (input) { this.prefix = input; this.echo = _.bind(this.echo, this); // function, context } function Foobar (input) { this.prefix = input; _.bindAll(this); // context } http://underscorejs.org/#bind
  • 32. Use $.proxy function Foobar (input) { this.prefix = input; this.echo = $.proxy(this.echo, this); // function, context } function Foobar (input) { this.prefix = input; this.echo = $.proxy(this, 'echo'); // context, method name } http://api.jquery.com/jQuery.proxy/
  • 33. Bind by Need fb = new Foobar(); $.get('/info', $.proxy(fb, 'echo')); $.get('/info', $.proxy(fb.echo, fb)); $.get('/info', $.bind(fb.echo, fb));
  • 36. Closure var isIE = true; function foobar() { if (!isIE) { // access isIE is possible because of closure return; } // blah... };
  • 37. that/self function Foobar(input) { var that = this; // that or self this.prefix = input; this.echo = function (result) { return that.prefix + result; // that is accessible because of closure }; } fb = new Foobar('res: '); $.get('/info', fb.echo);
  • 38. CoffeeScript Fat Arrow Foobar = (input) -> @prefix = input @echo = (result) => @prefix + result fb = new Foobar('res: ') $.get('/info', fb.echo)
  • 39. CoffeeScript Fat Arrow Foobar = (input) -> @prefix = input @echo = (result) => @prefix + result fb = new Foobar('res: ') $.get('/info', fb.echo)
  • 40. Compile to JS var Foobar, fb; Foobar = function(input) { var _this = this; this.prefix = input; return this.echo = function(result) { return _this.prefix + result; }; }; fb = new Foobar('res: '); $.get('/info', fb.echo);
  • 41. Compile to JS var Foobar, fb; Foobar = function(input) { var _this = this; this.prefix = input; return this.echo = function(result) { return _this.prefix + result; }; }; fb = new Foobar('res: '); $.get('/info', fb.echo);
  • 42. Compile to JS var Foobar, fb; Foobar = function(input) { var _this = this; this.prefix = input; return this.echo = function(result) { return _this.prefix + result; }; }; fb = new Foobar('res: '); $.get('/info', fb.echo);
  • 44. Pros • No more this issue, context free • Reduce one call stack • No call/apply, no impact on performance • Encapsulation
  • 45. Cons • Can’t use this tip on normal constructor
  • 46. How about AMD • Dene modules can return constructor, function, array, primitive data • Dene a singleton module on most cases • Always have data on module
  • 47. AMD Singleton Module define('foobar', function () { return { init: function (prefix) { this.prefix = prefix; } echo: function (input) { return this.prefix + input; } }; });
  • 48. Cons • Function can be borrowed • Not doing on right `this` you expect
  • 49. Avoid Use this define('foobar', function () { var self = {}; return { init: function (prefix) { self.prefix = prefix; } echo: function (input) { return self.prefix + input; } }; });
  • 50. Constructors? • Use bind to protect methods if necessary
  • 51. Constructor Without this function Person(birth, gender) { var person = { birth: (birth || '1970/01/01'), gender: (gender || 'M') }; return { getBirth: function () { return person.birth; }, getGender: function () { return person.gender; } }; }
  • 52. to new or not to new var p1 = Person('2013/01/02'); p1.getBirth(); // "2013/01/02" var p2 = new Person('2000/01/02', 'F'); p2.getBirth(); // "2000/01/02" p1.getBirth(); // "2013/01/02"
  • 53. Cons • No prototype inheritance • More memory usage for methods
  • 54. Backbone Model define(function (require) { return Backbone.Model.extend( initialize: function (attrs) { return _.bindAll(this); }, toITEM: function () { return this.toJSON(); }, toConfig: function () { return { name: this.get('name'), package_name: this.get('package_name') }; } ); });
  • 55. Who Use this Tip • jQuery.Deferred • jQuery.Callbacks
  • 56. Deferred Chaining var firstDfd = $.Deferred(), secondDfd = $.Deferred(), thirdDfd = $.Deferred(); firstDfd.done(secondDfd.resolve); secondDfd.done(thirdDfd.resolve); firstDfd.resolve(); // All Deferred object resolved here
  • 57. Callbacks https://github.com/jquery/jquery/blob/master/src/deferred.js // promise[ done | fail | progress ] = list.add promise[ tuple[1] ] = list.add; // skip... // deferred[ resolve | reject | notify ] deferred[ tuple[0] ] = function() { deferred[ tuple[0] + "With" ] (this === deferred ? promise : this, arguments); return this; }; deferred[ tuple[0] + "With" ] = list.fireWith;
  • 58. Callbacks https://github.com/jquery/jquery/blob/master/src/deferred.js // promise[ done | fail | progress ] = list.add promise[ tuple[1] ] = list.add; // skip... // deferred[ resolve | reject | notify ] deferred[ tuple[0] ] = function() { deferred[ tuple[0] + "With" ] (this === deferred ? promise : this, arguments); return this; }; deferred[ tuple[0] + "With" ] = list.fireWith;
  • 59. Actually Are promise['done'] = resolveCallbacks.add; promise['fail'] = rejectCallbacks.add; promise['progress'] = notifyCallbacks.add; // skip... deferred["resolveWith"] = resolveCallbacks.fireWith; deferred["rejectWith"] = rejectCallbacks.fireWith; deferred["notifyWith"] = notifyCallbacks.fireWith;
  • 60. Summary • Understand `this` • Understand how not to use `this` • Use `this` carefully if necessary
  • 61. Trade-Off • ‘Not use this’ requires more memory on methods denition and not easy to inheritance object • Benet is you can write more clear, simple code