SlideShare uma empresa Scribd logo
1 de 64
Baixar para ler offline
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 definition 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/

Mais conteúdo relacionado

Mais procurados

Cycle.js: Functional and Reactive
Cycle.js: Functional and ReactiveCycle.js: Functional and Reactive
Cycle.js: Functional and ReactiveEugene Zharkov
 
Writing Clean Code in Swift
Writing Clean Code in SwiftWriting Clean Code in Swift
Writing Clean Code in SwiftDerek Lee Boire
 
ES6 PPT FOR 2016
ES6 PPT FOR 2016ES6 PPT FOR 2016
ES6 PPT FOR 2016Manoj Kumar
 
The Beauty Of Java Script V5a
The Beauty Of Java Script V5aThe Beauty Of Java Script V5a
The Beauty Of Java Script V5arajivmordani
 
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 6Dmitry Soshnikov
 
EcmaScript 6 - The future is here
EcmaScript 6 - The future is hereEcmaScript 6 - The future is here
EcmaScript 6 - The future is hereSebastiano Armeli
 
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 DevsRebecca Murphey
 
Mulberry: A Mobile App Development Toolkit
Mulberry: A Mobile App Development ToolkitMulberry: A Mobile App Development Toolkit
Mulberry: A Mobile App Development ToolkitRebecca Murphey
 
jQuery Namespace Pattern
jQuery Namespace PatternjQuery Namespace Pattern
jQuery Namespace PatternDiego Fleury
 
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 frameworkG Woo
 

Mais procurados (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
 

Destaque

Functions and Objects in JavaScript
Functions and Objects in JavaScript Functions and Objects in JavaScript
Functions and Objects in JavaScript Dhananjay Kumar
 
Javascript - Array - Writing
Javascript - Array - WritingJavascript - Array - Writing
Javascript - Array - WritingSamuel Santos
 
javascript objects
javascript objectsjavascript objects
javascript objectsVijay Kalyan
 
Javascript good parts - for novice programmers
Javascript good parts - for novice programmersJavascript good parts - for novice programmers
Javascript good parts - for novice programmersManohar Shetty
 
Javascript - Array - Creating Array
Javascript - Array - Creating ArrayJavascript - Array - Creating Array
Javascript - Array - Creating ArraySamuel Santos
 
Learn REST in 18 Slides
Learn REST in 18 SlidesLearn REST in 18 Slides
Learn REST in 18 SlidesSuraj Gupta
 
The JavaScript You Wished You Knew
The JavaScript You Wished You KnewThe JavaScript You Wished You Knew
The JavaScript You Wished You KnewTroy Miles
 
Good Parts of JavaScript Douglas Crockford
Good Parts of JavaScript Douglas CrockfordGood Parts of JavaScript Douglas Crockford
Good Parts of JavaScript Douglas Crockfordrajivmordani
 
JavaScript - From Birth To Closure
JavaScript - From Birth To ClosureJavaScript - From Birth To Closure
JavaScript - From Birth To ClosureRobert Nyman
 
Structure of url, uniform resource locator
Structure of url, uniform resource locatorStructure of url, uniform resource locator
Structure of url, uniform resource locatorPartnered Health
 
JavaScript Functions
JavaScript FunctionsJavaScript Functions
JavaScript FunctionsColin DeCarlo
 
Javascript para principiantes -Introducción
Javascript para principiantes -IntroducciónJavascript para principiantes -Introducción
Javascript para principiantes -IntroducciónOscar Josué Uh Pérez
 
Basics of computer science
Basics of computer scienceBasics of computer science
Basics of computer sciencePaul Schmidt
 

Destaque (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
 

Semelhante a this

Jsphp 110312161301-phpapp02
Jsphp 110312161301-phpapp02Jsphp 110312161301-phpapp02
Jsphp 110312161301-phpapp02Seri Moth
 
JavaScript for PHP developers
JavaScript for PHP developersJavaScript for PHP developers
JavaScript for PHP developersStoyan 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 Suckerockendude
 
Introduction to ECMAScript 2015
Introduction to ECMAScript 2015Introduction to ECMAScript 2015
Introduction to ECMAScript 2015Tomasz Dziuda
 
Javascript this keyword
Javascript this keywordJavascript this keyword
Javascript this keywordPham Huy Tung
 
Object Oriented JavaScript
Object Oriented JavaScriptObject Oriented JavaScript
Object Oriented JavaScriptDonald Sipe
 
Functional Programming in PHP
Functional Programming in PHPFunctional Programming in PHP
Functional Programming in PHPpwmosquito
 
Introducing PHP Latest Updates
Introducing PHP Latest UpdatesIntroducing PHP Latest Updates
Introducing PHP Latest UpdatesIftekhar Eather
 
Ian 20150116 java script oop
Ian 20150116 java script oopIan 20150116 java script oop
Ian 20150116 java script oopLearningTech
 
JSConf: All You Can Leet
JSConf: All You Can LeetJSConf: All You Can Leet
JSConf: All You Can Leetjohndaviddalton
 
JavaScript - Like a Box of Chocolates
JavaScript - Like a Box of ChocolatesJavaScript - Like a Box of Chocolates
JavaScript - Like a Box of ChocolatesRobert Nyman
 
Web Optimization Summit: Coding for Performance
Web Optimization Summit: Coding for PerformanceWeb Optimization Summit: Coding for Performance
Web Optimization Summit: Coding for Performancejohndaviddalton
 
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...Mathias Bynens
 

Semelhante a 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...
 

Mais de 偉格 高

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偉格 高
 
TOSSUG HTML5 讀書會 新標籤與表單
TOSSUG HTML5 讀書會 新標籤與表單TOSSUG HTML5 讀書會 新標籤與表單
TOSSUG HTML5 讀書會 新標籤與表單偉格 高
 
Html5 New Features
Html5 New FeaturesHtml5 New Features
Html5 New Features偉格 高
 

Mais de 偉格 高 (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
 

Último

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...Miguel Araújo
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerThousandEyes
 
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 Nanonetsnaman860154
 
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...Enterprise Knowledge
 
Slack Application Development 101 Slides
Slack Application Development 101 SlidesSlack Application Development 101 Slides
Slack Application Development 101 Slidespraypatel2
 
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdfThe Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdfEnterprise Knowledge
 
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
 
08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking Men08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking MenDelhi Call girls
 
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
 
The Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptxThe Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptxMalak Abu Hammad
 
GenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationGenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationMichael W. Hawkins
 
08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking Men08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking MenDelhi Call girls
 
CNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of ServiceCNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of Servicegiselly40
 
08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking Men08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking MenDelhi Call girls
 
🐬 The future of MySQL is Postgres 🐘
🐬  The future of MySQL is Postgres   🐘🐬  The future of MySQL is Postgres   🐘
🐬 The future of MySQL is Postgres 🐘RTylerCroy
 
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...
Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...Neo4j
 
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 MountPuma Security, LLC
 
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...Igalia
 
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptxHampshireHUG
 
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
 

Último (20)

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...
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected Worker
 
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
 
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...
 
Slack Application Development 101 Slides
Slack Application Development 101 SlidesSlack Application Development 101 Slides
Slack Application Development 101 Slides
 
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdfThe Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
 
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
 
08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking Men08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking Men
 
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)
 
The Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptxThe Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptx
 
GenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationGenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day Presentation
 
08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking Men08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking Men
 
CNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of ServiceCNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of Service
 
08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking Men08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking Men
 
🐬 The future of MySQL is Postgres 🐘
🐬  The future of MySQL is Postgres   🐘🐬  The future of MySQL is Postgres   🐘
🐬 The future of MySQL is Postgres 🐘
 
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...
Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...
 
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
 
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
 
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
 
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
 

this

  • 2.
  • 3. this • ‘the object’ it belongs in OOP
  • 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 • Define modules can return constructor, function, array, primitive data • Define 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 definition and not easy to inheritance object • Benefit is you can write more clear, simple code