SlideShare a Scribd company logo
運用Closure Compiler
打造高品質的JavaScript


      Hedger 王璽
前端工程師
 Yahoo! 2004 - 2008
Google 2008 - Present
適用場合
  Complex JS Application
Object-Oriented JavaScript
面向對象的 JavaScript
困境
缺乏類別 Class
// John Resig's Approach.
function User(name){
  if ( !(this instanceof User) )
    return new User(name);
  this.name = name;
}

var userA = new User('John'); // An instance.
var userB = User('Jane'); // Also an instance.
缺乏私有 @private
// Crockford's approach.
function User(name) {
  var _name = name;

    // Getter for the private name.
    this.getName = function() {
      return _name;
    };
}
缺乏包 Package
// Global is evil.
var myProjectDemoUserName = 'foo';

// Meeh...
my.project.demo.user.Name = 'foo';
缺乏伸縮性 scalability
jQuery
   MooTool
  prototype
script.aculo.us
      YUI
     ExtJS
     Dojo
    Closure
Functional OO?                or

var p1 = new Person('John');
var p2 = new Person('Jane');
var people = new People();
people.add(p1);
people.add(p2);
document.write(people.getCount());
<script src="http://yui.yahooapis.com/2.8.2r1/build/dom/dom-min.js"></script>


// YAHOO.util.DragDropMgr

/**
 * Returns the specified element style property
 * @method getStyle
 * @param {HTMLElement} el             the element
 * @param {string}       styleProp the style property
 * @return {string} The value of the style property
 * @deprecated use YAHOO.util.Dom.getStyle
 * @static
 */
getStyle: function(el, styleProp) {
   return YAHOO.util.Dom.getStyle(el, styleProp);
},
人人都是
JavaScript
  忍者
if (!('a' in window)) {
  var a = 1;
}
alert(a);
Closure
Compiler
It is a true compiler for JavaScript.
Instead of compiling from a source
language to machine code, it compiles
from JavaScript to better JavaScript. It
parses your JavaScript, analyzes it,
removes dead code and rewrites and
minimizes what’s left. It also checks
syntax, variable references, and types,
and warns about common JavaScript
pitfalls.
@constructor
/**
 * @constructor
 */
function MyClass() {
}

// Pass.
var obj1 = new MyClass();

// ERROR: Constructor function (this:MyClass):
// class should be called with the "new" keyword.
var obj2 = MyClass(); // Error.
@private
// File demo1.js                             // File demo2.js

/**                                          // Create a user.
 * A User.                                   var me = new User();
 * @constructor
 */                                          // Print out its birth year.
function User() {                            document.write(me.
                                                getBirthYear().toString());
    /**
     * The creation date.                    // Error
     * @private                              document.write(me.
     * @type {Date}                             _birthDay.toString());
     */
    this._birthDay = new Date();
}

/**
 * @return {number} The creation year.
 */
User.prototype.getBirthYear = function() {
  return this._birthDay.getYear();
};
@extend
/**
 * The shape
 * @constructor
 */
function Shape() {
}

/**
 * The Box.
 * @constructor
 * @extends {Shape}
 */
function Box()) {
}
@interface
@implements
/**
 * The shape
 * @constructor
 */
function Shape() {
}

/** @return {number} */
Shape.prototype.getSize = function() {};

/**
 * The Box.
 * @constructor
 * @imnplements {Shape}
 */
function Box()) {
}
/** @inheritDoc */
Box.prototype.getSize = function() {return 0;};
命名空
package & namespace
// Create namespaces.
var demo = {};
demo.example = {};
demo.example.exercise = {};

/**
 * @constructor
 */
demo.example.exercise.Foo = function() {
  demo.example.exercise.Foo.print(this.value1);
  demo.example.exercise.Foo.print(this.value2);
};
STRICT type checking
  嚴格的類型檢查
function User() {
}

function UsersGroup() {
  this.users_ = [];
}

UsersGroup.prototype.add = function(user) {
 // Make sure that only user can be added.
 if (!(user instanceof User)) {
   throw new Error('Only user can be added.');
 }
 this.users_.push(user);
};

var me = new User();
var myGroup = new UsersGroup();
myGroup.add(me);
/**
 * @constructor
 */
function User() {
}

/**
 * @constructor
 */
function UsersGroup() {
  /**
   * @private
   * @type {Array.<User>}
   */
  this.users_ = [];
}

/**
* @param {User} user
*/
UsersGroup.prototype.add = function(user) {
 this.users_.push(user);
};
@enum
function Project(status) {
  this.status_ = status;
}

Project.prototype.isBusy = function() {
  switch (this.status_) {
    case 'busy':;
    case 'super_busy':
     return true;
    default:
     return false;
  }
};

var p1 = new Project('busy');
var p2 = new Project('super_busy');
var p3 = new Project('idle');

document.write(p1.isBusy().toString());
document.write(p2.isBusy().toString());
document.write(p3.isBusy().toString());
/**
 * @constructor
 * @param {Project.Status} status
 */
function Project(status) {          /**
  /**                                * @return {boolean}
   * @type {Project.Status}          */
   * @private                       Project.prototype.isBusy = function() {
   */                                switch (this.status_) {
  this.status_ = status;               case Project.Status.BUSY:;
}                                      case Project.Status.SUPER_BUSY:
                                        return true;
/**                                    default:
 * @enum {number}                       return false;
 */                                  }
Project.Status = {                  };
  BUSY: 0,
  SUPER_BUSY: 1,                    var p1 = new Project(Project.Status.BUSY);
  IDLE: 2                           var p2 = new Project(
};                                    Project.Status.SUPER_BUSY);
                                    var p3 = new Project(Project.Status.IDLE);

                                    document.write(p1.isBusy().toString());
                                    document.write(p2.isBusy().toString());
                                    document.write(p3.isBusy().toString());
@define
/**
 * namespace for the Logger.
 */
var Logger = {};

/**
 * Whether logging should be
 * enabled.                                       /**
 * @define {boolean}                               * A User.
 */                                                * @param {string} name
Logger.ENABLED = true;                             * @constructor
                                                   */
/**                                               function LoggerUser(name) {
 * the log API.                                     Logger.log('New User', name);
 * @param {...*} args                             }
 */
Logger.log = function(args) {                     var me = new LoggerUser('me');
  if (!Logger.ENABLED) {
    // Don't do anything if logger is disabled.
    return;
  }
  var console = window['console'];
  if (console) {
    console['log'].apply(console, arguments);
  }
};
@casting
/**                                             /**
 * The Model definition.                         * A static method that creates a
 * @constructor                                  * User from a model.
 */                                              * @param {UserModel} model
function UserModel() {                           * @return {User} The user created.
  /**                                            */
   * @type {string}                             User.createFromUserModel =
   */                                              function(model) {
  this.firstName = '';                           return new User(
                                                    model.firstName,
    /**                                             model.lastName);
     * @type {string}                           };
     */
    this.lastName = '';
                                                // Cast a simple JSON Object as
}
                                                // {UserModel}.
/**                                             var data = /** @type {UserModel} */({
 * The User constructor.                          firstName : 'foo',
 * @constructor                                   lastName : 'bar'
 * @param {string} firstName                    });
 * @param {string} lastName
 */                                             // Create a user from the model.
function User(firstName,                        var user = User.createFromUserModel(data);
           lastName) {                          document.write(user.fullName);
  /**
   * @type {string}
   */
  this.fullName = firstName + ' ' + lastName;
}
總結
良好的代碼風格
可讀性 / 可維護性 / 可用性
Developer, IDE, Compiler, JSDocBuilder
詳細合理的註釋
progressive enhancemen
良好的開發週期
開發/測試/發佈
保持嚴謹
展望
JavaScript
  Everywhere

PS3 . iPhone . Android
 ChromeOS . WebOS
JavaScript
    Everything
Mobile App . Game . RIA
謝謝
大家

More Related Content

What's hot

Advanced JavaScript Concepts
Advanced JavaScript ConceptsAdvanced JavaScript Concepts
Advanced JavaScript Concepts
Naresh Kumar
 
Funcitonal Swift Conference: The Functional Way
Funcitonal Swift Conference: The Functional WayFuncitonal Swift Conference: The Functional Way
Funcitonal Swift Conference: The Functional Way
Natasha Murashev
 
Advanced JavaScript
Advanced JavaScriptAdvanced JavaScript
Advanced JavaScript
Nascenia IT
 
data Structure Lecture 1
data Structure Lecture 1data Structure Lecture 1
data Structure Lecture 1
Teksify
 
Ian 20150116 java script oop
Ian 20150116 java script oopIan 20150116 java script oop
Ian 20150116 java script oop
LearningTech
 
Callbacks, Promises, and Coroutines (oh my!): Asynchronous Programming Patter...
Callbacks, Promises, and Coroutines (oh my!): Asynchronous Programming Patter...Callbacks, Promises, and Coroutines (oh my!): Asynchronous Programming Patter...
Callbacks, Promises, and Coroutines (oh my!): Asynchronous Programming Patter...
Domenic Denicola
 
Workshop 1: Good practices in JavaScript
Workshop 1: Good practices in JavaScriptWorkshop 1: Good practices in JavaScript
Workshop 1: Good practices in JavaScript
Visual Engineering
 
Fundamental JavaScript [UTC, March 2014]
Fundamental JavaScript [UTC, March 2014]Fundamental JavaScript [UTC, March 2014]
Fundamental JavaScript [UTC, March 2014]
Aaron Gustafson
 
Building an api using golang and postgre sql v1.0
Building an api using golang and postgre sql v1.0Building an api using golang and postgre sql v1.0
Building an api using golang and postgre sql v1.0
Frost
 
Workshop 5: JavaScript testing
Workshop 5: JavaScript testingWorkshop 5: JavaScript testing
Workshop 5: JavaScript testing
Visual Engineering
 
Java script
Java scriptJava script
Java script
Adrian Caetano
 
5 Tips for Better JavaScript
5 Tips for Better JavaScript5 Tips for Better JavaScript
5 Tips for Better JavaScript
Todd Anglin
 
Powerful JavaScript Tips and Best Practices
Powerful JavaScript Tips and Best PracticesPowerful JavaScript Tips and Best Practices
Powerful JavaScript Tips and Best Practices
Dragos Ionita
 
Net/http and the http.handler interface
Net/http and the http.handler interfaceNet/http and the http.handler interface
Net/http and the http.handler interface
Joakim Gustin
 
JavaScript Tutorial
JavaScript  TutorialJavaScript  Tutorial
JavaScript Tutorial
Bui Kiet
 
Practical JavaScript Programming - Session 1/8
Practical JavaScript Programming - Session 1/8Practical JavaScript Programming - Session 1/8
Practical JavaScript Programming - Session 1/8
Wilson Su
 
Workshop 10: ECMAScript 6
Workshop 10: ECMAScript 6Workshop 10: ECMAScript 6
Workshop 10: ECMAScript 6
Visual Engineering
 

What's hot (20)

Intro to JavaScript
Intro to JavaScriptIntro to JavaScript
Intro to JavaScript
 
Advanced JavaScript Concepts
Advanced JavaScript ConceptsAdvanced JavaScript Concepts
Advanced JavaScript Concepts
 
Funcitonal Swift Conference: The Functional Way
Funcitonal Swift Conference: The Functional WayFuncitonal Swift Conference: The Functional Way
Funcitonal Swift Conference: The Functional Way
 
Java Script Best Practices
Java Script Best PracticesJava Script Best Practices
Java Script Best Practices
 
Advanced JavaScript
Advanced JavaScriptAdvanced JavaScript
Advanced JavaScript
 
Javascript
JavascriptJavascript
Javascript
 
data Structure Lecture 1
data Structure Lecture 1data Structure Lecture 1
data Structure Lecture 1
 
Ian 20150116 java script oop
Ian 20150116 java script oopIan 20150116 java script oop
Ian 20150116 java script oop
 
Callbacks, Promises, and Coroutines (oh my!): Asynchronous Programming Patter...
Callbacks, Promises, and Coroutines (oh my!): Asynchronous Programming Patter...Callbacks, Promises, and Coroutines (oh my!): Asynchronous Programming Patter...
Callbacks, Promises, and Coroutines (oh my!): Asynchronous Programming Patter...
 
Workshop 1: Good practices in JavaScript
Workshop 1: Good practices in JavaScriptWorkshop 1: Good practices in JavaScript
Workshop 1: Good practices in JavaScript
 
Fundamental JavaScript [UTC, March 2014]
Fundamental JavaScript [UTC, March 2014]Fundamental JavaScript [UTC, March 2014]
Fundamental JavaScript [UTC, March 2014]
 
Building an api using golang and postgre sql v1.0
Building an api using golang and postgre sql v1.0Building an api using golang and postgre sql v1.0
Building an api using golang and postgre sql v1.0
 
Workshop 5: JavaScript testing
Workshop 5: JavaScript testingWorkshop 5: JavaScript testing
Workshop 5: JavaScript testing
 
Java script
Java scriptJava script
Java script
 
5 Tips for Better JavaScript
5 Tips for Better JavaScript5 Tips for Better JavaScript
5 Tips for Better JavaScript
 
Powerful JavaScript Tips and Best Practices
Powerful JavaScript Tips and Best PracticesPowerful JavaScript Tips and Best Practices
Powerful JavaScript Tips and Best Practices
 
Net/http and the http.handler interface
Net/http and the http.handler interfaceNet/http and the http.handler interface
Net/http and the http.handler interface
 
JavaScript Tutorial
JavaScript  TutorialJavaScript  Tutorial
JavaScript Tutorial
 
Practical JavaScript Programming - Session 1/8
Practical JavaScript Programming - Session 1/8Practical JavaScript Programming - Session 1/8
Practical JavaScript Programming - Session 1/8
 
Workshop 10: ECMAScript 6
Workshop 10: ECMAScript 6Workshop 10: ECMAScript 6
Workshop 10: ECMAScript 6
 

Viewers also liked

Webdistilled Social500
Webdistilled Social500Webdistilled Social500
Webdistilled Social500
Vieri Emiliani
 
Mauna (Silence) & Superliving Dr Shriniwas Kashalikar
Mauna (Silence) & Superliving  Dr Shriniwas KashalikarMauna (Silence) & Superliving  Dr Shriniwas Kashalikar
Mauna (Silence) & Superliving Dr Shriniwas Kashalikarshriniwaskashalikar
 
幸運星繁體簡報
幸運星繁體簡報幸運星繁體簡報
幸運星繁體簡報
guest74e2881
 
世界奇特建築
世界奇特建築世界奇特建築
世界奇特建築Josephine C
 
Webdistilled Social500
Webdistilled Social500Webdistilled Social500
Webdistilled Social500
Vieri Emiliani
 
Validating MSI Updates and Patches
Validating MSI Updates and PatchesValidating MSI Updates and Patches
Validating MSI Updates and Patches
Flexera
 
Classroom Management
Classroom ManagementClassroom Management
Classroom ManagementJ C
 
Personal Branding For Job Seekers
Personal Branding For Job SeekersPersonal Branding For Job Seekers
Personal Branding For Job Seekers
Stephen Murphy
 
MijnZorgNet Jan Kremer
MijnZorgNet   Jan KremerMijnZorgNet   Jan Kremer
MijnZorgNet Jan KremerMijnZorgnet
 
Master key system part 14
Master key system   part 14Master key system   part 14
Master key system part 14canei2day
 
编辑器设计Kissy editor
编辑器设计Kissy editor编辑器设计Kissy editor
编辑器设计Kissy editortaobao.com
 
Direct and reported speech
Direct and reported speechDirect and reported speech
Direct and reported speechEunice Rivera
 
More weapons, more power
More weapons, more powerMore weapons, more power
More weapons, more powertaobao.com
 
Webdistilled API
Webdistilled APIWebdistilled API
Webdistilled API
Vieri Emiliani
 
Lead Generation on LinkedIn
Lead Generation on LinkedInLead Generation on LinkedIn
Lead Generation on LinkedIn
SEO, LLC dba www.SplinternetMarketing.com
 
Master key system landscape
Master key system landscapeMaster key system landscape
Master key system landscapecanei2day
 
Master key system part 04
Master key system   part 04Master key system   part 04
Master key system part 04canei2day
 

Viewers also liked (20)

Webdistilled Social500
Webdistilled Social500Webdistilled Social500
Webdistilled Social500
 
Corruption Shriniwas Kashalikar
Corruption Shriniwas KashalikarCorruption Shriniwas Kashalikar
Corruption Shriniwas Kashalikar
 
Mauna (Silence) & Superliving Dr Shriniwas Kashalikar
Mauna (Silence) & Superliving  Dr Shriniwas KashalikarMauna (Silence) & Superliving  Dr Shriniwas Kashalikar
Mauna (Silence) & Superliving Dr Shriniwas Kashalikar
 
幸運星繁體簡報
幸運星繁體簡報幸運星繁體簡報
幸運星繁體簡報
 
世界奇特建築
世界奇特建築世界奇特建築
世界奇特建築
 
Webdistilled Social500
Webdistilled Social500Webdistilled Social500
Webdistilled Social500
 
Validating MSI Updates and Patches
Validating MSI Updates and PatchesValidating MSI Updates and Patches
Validating MSI Updates and Patches
 
Splinternetmarketing Ranking Report Internet Marketing 2 28 2011
Splinternetmarketing Ranking Report Internet Marketing 2 28 2011Splinternetmarketing Ranking Report Internet Marketing 2 28 2011
Splinternetmarketing Ranking Report Internet Marketing 2 28 2011
 
Classroom Management
Classroom ManagementClassroom Management
Classroom Management
 
Personal Branding For Job Seekers
Personal Branding For Job SeekersPersonal Branding For Job Seekers
Personal Branding For Job Seekers
 
MijnZorgNet Jan Kremer
MijnZorgNet   Jan KremerMijnZorgNet   Jan Kremer
MijnZorgNet Jan Kremer
 
Master key system part 14
Master key system   part 14Master key system   part 14
Master key system part 14
 
编辑器设计Kissy editor
编辑器设计Kissy editor编辑器设计Kissy editor
编辑器设计Kissy editor
 
夜曝合歡山
夜曝合歡山夜曝合歡山
夜曝合歡山
 
Direct and reported speech
Direct and reported speechDirect and reported speech
Direct and reported speech
 
More weapons, more power
More weapons, more powerMore weapons, more power
More weapons, more power
 
Webdistilled API
Webdistilled APIWebdistilled API
Webdistilled API
 
Lead Generation on LinkedIn
Lead Generation on LinkedInLead Generation on LinkedIn
Lead Generation on LinkedIn
 
Master key system landscape
Master key system landscapeMaster key system landscape
Master key system landscape
 
Master key system part 04
Master key system   part 04Master key system   part 04
Master key system part 04
 

Similar to 運用Closure Compiler 打造高品質的JavaScript

Object Oriented JavaScript
Object Oriented JavaScriptObject Oriented JavaScript
Object Oriented JavaScript
Donald Sipe
 
6976.ppt
6976.ppt6976.ppt
Design patterns
Design patternsDesign patterns
Design patterns
Ba Tran
 
Email Program By Marcelo
Email Program By MarceloEmail Program By Marcelo
Email Program By Marcelo
Domingos Salvador
 
Email Program By Marcelo
Email Program By MarceloEmail Program By Marcelo
Email Program By Marcelo
Domingos Salvador
 
Email Program By Marcelo
Email Program By MarceloEmail Program By Marcelo
Email Program By Marcelo
Domingos Salvador
 
Object Oriented JavaScript
Object Oriented JavaScriptObject Oriented JavaScript
Object Oriented JavaScript
Michael Girouard
 
Enterprise js pratices
Enterprise js praticesEnterprise js pratices
Enterprise js pratices
Marjan Nikolovski
 
Jsp presentation
Jsp presentationJsp presentation
Jsp presentation
Sher Singh Bardhan
 
Production.javapublic class Production {    Declaring instance.pdf
Production.javapublic class Production {    Declaring instance.pdfProduction.javapublic class Production {    Declaring instance.pdf
Production.javapublic class Production {    Declaring instance.pdf
sooryasalini
 
Testando API's de forma unitária mocando as dependências
Testando API's de forma unitária mocando as dependênciasTestando API's de forma unitária mocando as dependências
Testando API's de forma unitária mocando as dependências
Marcelo Aymone
 
case3h231diamond.gifcase3h231energy.jpgcase3h231moder.docx
case3h231diamond.gifcase3h231energy.jpgcase3h231moder.docxcase3h231diamond.gifcase3h231energy.jpgcase3h231moder.docx
case3h231diamond.gifcase3h231energy.jpgcase3h231moder.docx
tidwellveronique
 
Library Project Marcelo Salvador
Library Project Marcelo SalvadorLibrary Project Marcelo Salvador
Library Project Marcelo Salvador
Domingos Salvador
 
Code to copy Person.java .pdf
Code to copy Person.java .pdfCode to copy Person.java .pdf
Code to copy Person.java .pdf
anokhijew
 
Fluent Development with FLOW3 1.0
Fluent Development with FLOW3 1.0Fluent Development with FLOW3 1.0
Fluent Development with FLOW3 1.0
Robert Lemke
 
Java script object model
Java script object modelJava script object model
Java script object modelJames Hsieh
 
Jggug 2010 330 Grails 1.3 観察
Jggug 2010 330 Grails 1.3 観察Jggug 2010 330 Grails 1.3 観察
Jggug 2010 330 Grails 1.3 観察Tsuyoshi Yamamoto
 
Ad java prac sol set
Ad java prac sol setAd java prac sol set
Ad java prac sol set
Iram Ramrajkar
 
Say It With Javascript
Say It With JavascriptSay It With Javascript
Say It With Javascript
Giovanni Scerra ☃
 

Similar to 運用Closure Compiler 打造高品質的JavaScript (20)

Object Oriented JavaScript
Object Oriented JavaScriptObject Oriented JavaScript
Object Oriented JavaScript
 
6976.ppt
6976.ppt6976.ppt
6976.ppt
 
Design patterns
Design patternsDesign patterns
Design patterns
 
Email Program By Marcelo
Email Program By MarceloEmail Program By Marcelo
Email Program By Marcelo
 
Email Program By Marcelo
Email Program By MarceloEmail Program By Marcelo
Email Program By Marcelo
 
Email Program By Marcelo
Email Program By MarceloEmail Program By Marcelo
Email Program By Marcelo
 
Object Oriented JavaScript
Object Oriented JavaScriptObject Oriented JavaScript
Object Oriented JavaScript
 
Enterprise js pratices
Enterprise js praticesEnterprise js pratices
Enterprise js pratices
 
Jsp presentation
Jsp presentationJsp presentation
Jsp presentation
 
Production.javapublic class Production {    Declaring instance.pdf
Production.javapublic class Production {    Declaring instance.pdfProduction.javapublic class Production {    Declaring instance.pdf
Production.javapublic class Production {    Declaring instance.pdf
 
Testando API's de forma unitária mocando as dependências
Testando API's de forma unitária mocando as dependênciasTestando API's de forma unitária mocando as dependências
Testando API's de forma unitária mocando as dependências
 
case3h231diamond.gifcase3h231energy.jpgcase3h231moder.docx
case3h231diamond.gifcase3h231energy.jpgcase3h231moder.docxcase3h231diamond.gifcase3h231energy.jpgcase3h231moder.docx
case3h231diamond.gifcase3h231energy.jpgcase3h231moder.docx
 
Library Project Marcelo Salvador
Library Project Marcelo SalvadorLibrary Project Marcelo Salvador
Library Project Marcelo Salvador
 
Code to copy Person.java .pdf
Code to copy Person.java .pdfCode to copy Person.java .pdf
Code to copy Person.java .pdf
 
Fluent Development with FLOW3 1.0
Fluent Development with FLOW3 1.0Fluent Development with FLOW3 1.0
Fluent Development with FLOW3 1.0
 
Java script object model
Java script object modelJava script object model
Java script object model
 
Week 12 code
Week 12 codeWeek 12 code
Week 12 code
 
Jggug 2010 330 Grails 1.3 観察
Jggug 2010 330 Grails 1.3 観察Jggug 2010 330 Grails 1.3 観察
Jggug 2010 330 Grails 1.3 観察
 
Ad java prac sol set
Ad java prac sol setAd java prac sol set
Ad java prac sol set
 
Say It With Javascript
Say It With JavascriptSay It With Javascript
Say It With Javascript
 

More from taobao.com

编辑器设计U editor
编辑器设计U editor编辑器设计U editor
编辑器设计U editortaobao.com
 
淘宝开放产品前端实践
淘宝开放产品前端实践淘宝开放产品前端实践
淘宝开放产品前端实践taobao.com
 
广告投放代码和创意代码持续优化
广告投放代码和创意代码持续优化广告投放代码和创意代码持续优化
广告投放代码和创意代码持续优化taobao.com
 
第三方内容开发最佳实践
第三方内容开发最佳实践第三方内容开发最佳实践
第三方内容开发最佳实践taobao.com
 
百度前端性能监控与优化实践
百度前端性能监控与优化实践百度前端性能监控与优化实践
百度前端性能监控与优化实践taobao.com
 
Node.js在淘宝的应用实践
Node.js在淘宝的应用实践Node.js在淘宝的应用实践
Node.js在淘宝的应用实践taobao.com
 
Kind editor设计思路
Kind editor设计思路Kind editor设计思路
Kind editor设计思路taobao.com
 
Java script physical engine
Java script physical engineJava script physical engine
Java script physical enginetaobao.com
 
Html5环保小游戏
Html5环保小游戏Html5环保小游戏
Html5环保小游戏taobao.com
 
阅读类Web应用前端技术探索
阅读类Web应用前端技术探索阅读类Web应用前端技术探索
阅读类Web应用前端技术探索taobao.com
 
完颜:移动网站的兼容性探索
完颜:移动网站的兼容性探索完颜:移动网站的兼容性探索
完颜:移动网站的兼容性探索taobao.com
 
张平:JavaScript引擎实现
张平:JavaScript引擎实现张平:JavaScript引擎实现
张平:JavaScript引擎实现taobao.com
 
高力:19楼现有前端架构
高力:19楼现有前端架构高力:19楼现有前端架构
高力:19楼现有前端架构taobao.com
 
李成银:前端编译平台
李成银:前端编译平台李成银:前端编译平台
李成银:前端编译平台taobao.com
 
钱宝坤:多浏览器集成的JavaScript单元测试工具
钱宝坤:多浏览器集成的JavaScript单元测试工具钱宝坤:多浏览器集成的JavaScript单元测试工具
钱宝坤:多浏览器集成的JavaScript单元测试工具taobao.com
 
张克军:前端基础架构的实践和思考
张克军:前端基础架构的实践和思考张克军:前端基础架构的实践和思考
张克军:前端基础架构的实践和思考taobao.com
 
刘平川:【用户行为分析】Marmot实践
刘平川:【用户行为分析】Marmot实践刘平川:【用户行为分析】Marmot实践
刘平川:【用户行为分析】Marmot实践taobao.com
 
吴英杰:【用户行为分析】淘宝页面显微镜系统原理及实践
吴英杰:【用户行为分析】淘宝页面显微镜系统原理及实践吴英杰:【用户行为分析】淘宝页面显微镜系统原理及实践
吴英杰:【用户行为分析】淘宝页面显微镜系统原理及实践taobao.com
 
前端Mvc探讨及实践
前端Mvc探讨及实践前端Mvc探讨及实践
前端Mvc探讨及实践taobao.com
 

More from taobao.com (20)

编辑器设计U editor
编辑器设计U editor编辑器设计U editor
编辑器设计U editor
 
Berserk js
Berserk jsBerserk js
Berserk js
 
淘宝开放产品前端实践
淘宝开放产品前端实践淘宝开放产品前端实践
淘宝开放产品前端实践
 
广告投放代码和创意代码持续优化
广告投放代码和创意代码持续优化广告投放代码和创意代码持续优化
广告投放代码和创意代码持续优化
 
第三方内容开发最佳实践
第三方内容开发最佳实践第三方内容开发最佳实践
第三方内容开发最佳实践
 
百度前端性能监控与优化实践
百度前端性能监控与优化实践百度前端性能监控与优化实践
百度前端性能监控与优化实践
 
Node.js在淘宝的应用实践
Node.js在淘宝的应用实践Node.js在淘宝的应用实践
Node.js在淘宝的应用实践
 
Kind editor设计思路
Kind editor设计思路Kind editor设计思路
Kind editor设计思路
 
Java script physical engine
Java script physical engineJava script physical engine
Java script physical engine
 
Html5环保小游戏
Html5环保小游戏Html5环保小游戏
Html5环保小游戏
 
阅读类Web应用前端技术探索
阅读类Web应用前端技术探索阅读类Web应用前端技术探索
阅读类Web应用前端技术探索
 
完颜:移动网站的兼容性探索
完颜:移动网站的兼容性探索完颜:移动网站的兼容性探索
完颜:移动网站的兼容性探索
 
张平:JavaScript引擎实现
张平:JavaScript引擎实现张平:JavaScript引擎实现
张平:JavaScript引擎实现
 
高力:19楼现有前端架构
高力:19楼现有前端架构高力:19楼现有前端架构
高力:19楼现有前端架构
 
李成银:前端编译平台
李成银:前端编译平台李成银:前端编译平台
李成银:前端编译平台
 
钱宝坤:多浏览器集成的JavaScript单元测试工具
钱宝坤:多浏览器集成的JavaScript单元测试工具钱宝坤:多浏览器集成的JavaScript单元测试工具
钱宝坤:多浏览器集成的JavaScript单元测试工具
 
张克军:前端基础架构的实践和思考
张克军:前端基础架构的实践和思考张克军:前端基础架构的实践和思考
张克军:前端基础架构的实践和思考
 
刘平川:【用户行为分析】Marmot实践
刘平川:【用户行为分析】Marmot实践刘平川:【用户行为分析】Marmot实践
刘平川:【用户行为分析】Marmot实践
 
吴英杰:【用户行为分析】淘宝页面显微镜系统原理及实践
吴英杰:【用户行为分析】淘宝页面显微镜系统原理及实践吴英杰:【用户行为分析】淘宝页面显微镜系统原理及实践
吴英杰:【用户行为分析】淘宝页面显微镜系统原理及实践
 
前端Mvc探讨及实践
前端Mvc探讨及实践前端Mvc探讨及实践
前端Mvc探讨及实践
 

Recently uploaded

AI for Every Business: Unlocking Your Product's Universal Potential by VP of ...
AI for Every Business: Unlocking Your Product's Universal Potential by VP of ...AI for Every Business: Unlocking Your Product's Universal Potential by VP of ...
AI for Every Business: Unlocking Your Product's Universal Potential by VP of ...
Product School
 
ODC, Data Fabric and Architecture User Group
ODC, Data Fabric and Architecture User GroupODC, Data Fabric and Architecture User Group
ODC, Data Fabric and Architecture User Group
CatarinaPereira64715
 
Dev Dives: Train smarter, not harder – active learning and UiPath LLMs for do...
Dev Dives: Train smarter, not harder – active learning and UiPath LLMs for do...Dev Dives: Train smarter, not harder – active learning and UiPath LLMs for do...
Dev Dives: Train smarter, not harder – active learning and UiPath LLMs for do...
UiPathCommunity
 
UiPath Test Automation using UiPath Test Suite series, part 3
UiPath Test Automation using UiPath Test Suite series, part 3UiPath Test Automation using UiPath Test Suite series, part 3
UiPath Test Automation using UiPath Test Suite series, part 3
DianaGray10
 
How world-class product teams are winning in the AI era by CEO and Founder, P...
How world-class product teams are winning in the AI era by CEO and Founder, P...How world-class product teams are winning in the AI era by CEO and Founder, P...
How world-class product teams are winning in the AI era by CEO and Founder, P...
Product School
 
FIDO Alliance Osaka Seminar: Passkeys at Amazon.pdf
FIDO Alliance Osaka Seminar: Passkeys at Amazon.pdfFIDO Alliance Osaka Seminar: Passkeys at Amazon.pdf
FIDO Alliance Osaka Seminar: Passkeys at Amazon.pdf
FIDO Alliance
 
Unsubscribed: Combat Subscription Fatigue With a Membership Mentality by Head...
Unsubscribed: Combat Subscription Fatigue With a Membership Mentality by Head...Unsubscribed: Combat Subscription Fatigue With a Membership Mentality by Head...
Unsubscribed: Combat Subscription Fatigue With a Membership Mentality by Head...
Product School
 
FIDO Alliance Osaka Seminar: Passkeys and the Road Ahead.pdf
FIDO Alliance Osaka Seminar: Passkeys and the Road Ahead.pdfFIDO Alliance Osaka Seminar: Passkeys and the Road Ahead.pdf
FIDO Alliance Osaka Seminar: Passkeys and the Road Ahead.pdf
FIDO Alliance
 
Essentials of Automations: Optimizing FME Workflows with Parameters
Essentials of Automations: Optimizing FME Workflows with ParametersEssentials of Automations: Optimizing FME Workflows with Parameters
Essentials of Automations: Optimizing FME Workflows with Parameters
Safe Software
 
Smart TV Buyer Insights Survey 2024 by 91mobiles.pdf
Smart TV Buyer Insights Survey 2024 by 91mobiles.pdfSmart TV Buyer Insights Survey 2024 by 91mobiles.pdf
Smart TV Buyer Insights Survey 2024 by 91mobiles.pdf
91mobiles
 
The Future of Platform Engineering
The Future of Platform EngineeringThe Future of Platform Engineering
The Future of Platform Engineering
Jemma Hussein Allen
 
Accelerate your Kubernetes clusters with Varnish Caching
Accelerate your Kubernetes clusters with Varnish CachingAccelerate your Kubernetes clusters with Varnish Caching
Accelerate your Kubernetes clusters with Varnish Caching
Thijs Feryn
 
Designing Great Products: The Power of Design and Leadership by Chief Designe...
Designing Great Products: The Power of Design and Leadership by Chief Designe...Designing Great Products: The Power of Design and Leadership by Chief Designe...
Designing Great Products: The Power of Design and Leadership by Chief Designe...
Product School
 
Leading Change strategies and insights for effective change management pdf 1.pdf
Leading Change strategies and insights for effective change management pdf 1.pdfLeading Change strategies and insights for effective change management pdf 1.pdf
Leading Change strategies and insights for effective change management pdf 1.pdf
OnBoard
 
Kubernetes & AI - Beauty and the Beast !?! @KCD Istanbul 2024
Kubernetes & AI - Beauty and the Beast !?! @KCD Istanbul 2024Kubernetes & AI - Beauty and the Beast !?! @KCD Istanbul 2024
Kubernetes & AI - Beauty and the Beast !?! @KCD Istanbul 2024
Tobias Schneck
 
Empowering NextGen Mobility via Large Action Model Infrastructure (LAMI): pav...
Empowering NextGen Mobility via Large Action Model Infrastructure (LAMI): pav...Empowering NextGen Mobility via Large Action Model Infrastructure (LAMI): pav...
Empowering NextGen Mobility via Large Action Model Infrastructure (LAMI): pav...
Thierry Lestable
 
DevOps and Testing slides at DASA Connect
DevOps and Testing slides at DASA ConnectDevOps and Testing slides at DASA Connect
DevOps and Testing slides at DASA Connect
Kari Kakkonen
 
State of ICS and IoT Cyber Threat Landscape Report 2024 preview
State of ICS and IoT Cyber Threat Landscape Report 2024 previewState of ICS and IoT Cyber Threat Landscape Report 2024 preview
State of ICS and IoT Cyber Threat Landscape Report 2024 preview
Prayukth K V
 
PHP Frameworks: I want to break free (IPC Berlin 2024)
PHP Frameworks: I want to break free (IPC Berlin 2024)PHP Frameworks: I want to break free (IPC Berlin 2024)
PHP Frameworks: I want to break free (IPC Berlin 2024)
Ralf Eggert
 
The Art of the Pitch: WordPress Relationships and Sales
The Art of the Pitch: WordPress Relationships and SalesThe Art of the Pitch: WordPress Relationships and Sales
The Art of the Pitch: WordPress Relationships and Sales
Laura Byrne
 

Recently uploaded (20)

AI for Every Business: Unlocking Your Product's Universal Potential by VP of ...
AI for Every Business: Unlocking Your Product's Universal Potential by VP of ...AI for Every Business: Unlocking Your Product's Universal Potential by VP of ...
AI for Every Business: Unlocking Your Product's Universal Potential by VP of ...
 
ODC, Data Fabric and Architecture User Group
ODC, Data Fabric and Architecture User GroupODC, Data Fabric and Architecture User Group
ODC, Data Fabric and Architecture User Group
 
Dev Dives: Train smarter, not harder – active learning and UiPath LLMs for do...
Dev Dives: Train smarter, not harder – active learning and UiPath LLMs for do...Dev Dives: Train smarter, not harder – active learning and UiPath LLMs for do...
Dev Dives: Train smarter, not harder – active learning and UiPath LLMs for do...
 
UiPath Test Automation using UiPath Test Suite series, part 3
UiPath Test Automation using UiPath Test Suite series, part 3UiPath Test Automation using UiPath Test Suite series, part 3
UiPath Test Automation using UiPath Test Suite series, part 3
 
How world-class product teams are winning in the AI era by CEO and Founder, P...
How world-class product teams are winning in the AI era by CEO and Founder, P...How world-class product teams are winning in the AI era by CEO and Founder, P...
How world-class product teams are winning in the AI era by CEO and Founder, P...
 
FIDO Alliance Osaka Seminar: Passkeys at Amazon.pdf
FIDO Alliance Osaka Seminar: Passkeys at Amazon.pdfFIDO Alliance Osaka Seminar: Passkeys at Amazon.pdf
FIDO Alliance Osaka Seminar: Passkeys at Amazon.pdf
 
Unsubscribed: Combat Subscription Fatigue With a Membership Mentality by Head...
Unsubscribed: Combat Subscription Fatigue With a Membership Mentality by Head...Unsubscribed: Combat Subscription Fatigue With a Membership Mentality by Head...
Unsubscribed: Combat Subscription Fatigue With a Membership Mentality by Head...
 
FIDO Alliance Osaka Seminar: Passkeys and the Road Ahead.pdf
FIDO Alliance Osaka Seminar: Passkeys and the Road Ahead.pdfFIDO Alliance Osaka Seminar: Passkeys and the Road Ahead.pdf
FIDO Alliance Osaka Seminar: Passkeys and the Road Ahead.pdf
 
Essentials of Automations: Optimizing FME Workflows with Parameters
Essentials of Automations: Optimizing FME Workflows with ParametersEssentials of Automations: Optimizing FME Workflows with Parameters
Essentials of Automations: Optimizing FME Workflows with Parameters
 
Smart TV Buyer Insights Survey 2024 by 91mobiles.pdf
Smart TV Buyer Insights Survey 2024 by 91mobiles.pdfSmart TV Buyer Insights Survey 2024 by 91mobiles.pdf
Smart TV Buyer Insights Survey 2024 by 91mobiles.pdf
 
The Future of Platform Engineering
The Future of Platform EngineeringThe Future of Platform Engineering
The Future of Platform Engineering
 
Accelerate your Kubernetes clusters with Varnish Caching
Accelerate your Kubernetes clusters with Varnish CachingAccelerate your Kubernetes clusters with Varnish Caching
Accelerate your Kubernetes clusters with Varnish Caching
 
Designing Great Products: The Power of Design and Leadership by Chief Designe...
Designing Great Products: The Power of Design and Leadership by Chief Designe...Designing Great Products: The Power of Design and Leadership by Chief Designe...
Designing Great Products: The Power of Design and Leadership by Chief Designe...
 
Leading Change strategies and insights for effective change management pdf 1.pdf
Leading Change strategies and insights for effective change management pdf 1.pdfLeading Change strategies and insights for effective change management pdf 1.pdf
Leading Change strategies and insights for effective change management pdf 1.pdf
 
Kubernetes & AI - Beauty and the Beast !?! @KCD Istanbul 2024
Kubernetes & AI - Beauty and the Beast !?! @KCD Istanbul 2024Kubernetes & AI - Beauty and the Beast !?! @KCD Istanbul 2024
Kubernetes & AI - Beauty and the Beast !?! @KCD Istanbul 2024
 
Empowering NextGen Mobility via Large Action Model Infrastructure (LAMI): pav...
Empowering NextGen Mobility via Large Action Model Infrastructure (LAMI): pav...Empowering NextGen Mobility via Large Action Model Infrastructure (LAMI): pav...
Empowering NextGen Mobility via Large Action Model Infrastructure (LAMI): pav...
 
DevOps and Testing slides at DASA Connect
DevOps and Testing slides at DASA ConnectDevOps and Testing slides at DASA Connect
DevOps and Testing slides at DASA Connect
 
State of ICS and IoT Cyber Threat Landscape Report 2024 preview
State of ICS and IoT Cyber Threat Landscape Report 2024 previewState of ICS and IoT Cyber Threat Landscape Report 2024 preview
State of ICS and IoT Cyber Threat Landscape Report 2024 preview
 
PHP Frameworks: I want to break free (IPC Berlin 2024)
PHP Frameworks: I want to break free (IPC Berlin 2024)PHP Frameworks: I want to break free (IPC Berlin 2024)
PHP Frameworks: I want to break free (IPC Berlin 2024)
 
The Art of the Pitch: WordPress Relationships and Sales
The Art of the Pitch: WordPress Relationships and SalesThe Art of the Pitch: WordPress Relationships and Sales
The Art of the Pitch: WordPress Relationships and Sales
 

運用Closure Compiler 打造高品質的JavaScript

  • 2. 前端工程師 Yahoo! 2004 - 2008 Google 2008 - Present
  • 3. 適用場合 Complex JS Application Object-Oriented JavaScript
  • 7. // John Resig's Approach. function User(name){ if ( !(this instanceof User) ) return new User(name); this.name = name; } var userA = new User('John'); // An instance. var userB = User('Jane'); // Also an instance.
  • 9. // Crockford's approach. function User(name) { var _name = name; // Getter for the private name. this.getName = function() { return _name; }; }
  • 11. // Global is evil. var myProjectDemoUserName = 'foo'; // Meeh... my.project.demo.user.Name = 'foo';
  • 13. jQuery MooTool prototype script.aculo.us YUI ExtJS Dojo Closure
  • 14. Functional OO? or var p1 = new Person('John'); var p2 = new Person('Jane'); var people = new People(); people.add(p1); people.add(p2); document.write(people.getCount());
  • 15. <script src="http://yui.yahooapis.com/2.8.2r1/build/dom/dom-min.js"></script> // YAHOO.util.DragDropMgr /** * Returns the specified element style property * @method getStyle * @param {HTMLElement} el the element * @param {string} styleProp the style property * @return {string} The value of the style property * @deprecated use YAHOO.util.Dom.getStyle * @static */ getStyle: function(el, styleProp) { return YAHOO.util.Dom.getStyle(el, styleProp); },
  • 17. if (!('a' in window)) { var a = 1; } alert(a);
  • 19. It is a true compiler for JavaScript. Instead of compiling from a source language to machine code, it compiles from JavaScript to better JavaScript. It parses your JavaScript, analyzes it, removes dead code and rewrites and minimizes what’s left. It also checks syntax, variable references, and types, and warns about common JavaScript pitfalls.
  • 21. /** * @constructor */ function MyClass() { } // Pass. var obj1 = new MyClass(); // ERROR: Constructor function (this:MyClass): // class should be called with the "new" keyword. var obj2 = MyClass(); // Error.
  • 23. // File demo1.js // File demo2.js /** // Create a user. * A User. var me = new User(); * @constructor */ // Print out its birth year. function User() { document.write(me. getBirthYear().toString()); /** * The creation date. // Error * @private document.write(me. * @type {Date} _birthDay.toString()); */ this._birthDay = new Date(); } /** * @return {number} The creation year. */ User.prototype.getBirthYear = function() { return this._birthDay.getYear(); };
  • 25. /** * The shape * @constructor */ function Shape() { } /** * The Box. * @constructor * @extends {Shape} */ function Box()) { }
  • 27. /** * The shape * @constructor */ function Shape() { } /** @return {number} */ Shape.prototype.getSize = function() {}; /** * The Box. * @constructor * @imnplements {Shape} */ function Box()) { } /** @inheritDoc */ Box.prototype.getSize = function() {return 0;};
  • 29. // Create namespaces. var demo = {}; demo.example = {}; demo.example.exercise = {}; /** * @constructor */ demo.example.exercise.Foo = function() { demo.example.exercise.Foo.print(this.value1); demo.example.exercise.Foo.print(this.value2); };
  • 30. STRICT type checking 嚴格的類型檢查
  • 31. function User() { } function UsersGroup() { this.users_ = []; } UsersGroup.prototype.add = function(user) { // Make sure that only user can be added. if (!(user instanceof User)) { throw new Error('Only user can be added.'); } this.users_.push(user); }; var me = new User(); var myGroup = new UsersGroup(); myGroup.add(me);
  • 32. /** * @constructor */ function User() { } /** * @constructor */ function UsersGroup() { /** * @private * @type {Array.<User>} */ this.users_ = []; } /** * @param {User} user */ UsersGroup.prototype.add = function(user) { this.users_.push(user); };
  • 33. @enum
  • 34. function Project(status) { this.status_ = status; } Project.prototype.isBusy = function() { switch (this.status_) { case 'busy':; case 'super_busy': return true; default: return false; } }; var p1 = new Project('busy'); var p2 = new Project('super_busy'); var p3 = new Project('idle'); document.write(p1.isBusy().toString()); document.write(p2.isBusy().toString()); document.write(p3.isBusy().toString());
  • 35. /** * @constructor * @param {Project.Status} status */ function Project(status) { /** /** * @return {boolean} * @type {Project.Status} */ * @private Project.prototype.isBusy = function() { */ switch (this.status_) { this.status_ = status; case Project.Status.BUSY:; } case Project.Status.SUPER_BUSY: return true; /** default: * @enum {number} return false; */ } Project.Status = { }; BUSY: 0, SUPER_BUSY: 1, var p1 = new Project(Project.Status.BUSY); IDLE: 2 var p2 = new Project( }; Project.Status.SUPER_BUSY); var p3 = new Project(Project.Status.IDLE); document.write(p1.isBusy().toString()); document.write(p2.isBusy().toString()); document.write(p3.isBusy().toString());
  • 37. /** * namespace for the Logger. */ var Logger = {}; /** * Whether logging should be * enabled. /** * @define {boolean} * A User. */ * @param {string} name Logger.ENABLED = true; * @constructor */ /** function LoggerUser(name) { * the log API. Logger.log('New User', name); * @param {...*} args } */ Logger.log = function(args) { var me = new LoggerUser('me'); if (!Logger.ENABLED) { // Don't do anything if logger is disabled. return; } var console = window['console']; if (console) { console['log'].apply(console, arguments); } };
  • 39. /** /** * The Model definition. * A static method that creates a * @constructor * User from a model. */ * @param {UserModel} model function UserModel() { * @return {User} The user created. /** */ * @type {string} User.createFromUserModel = */ function(model) { this.firstName = ''; return new User( model.firstName, /** model.lastName); * @type {string} }; */ this.lastName = ''; // Cast a simple JSON Object as } // {UserModel}. /** var data = /** @type {UserModel} */({ * The User constructor. firstName : 'foo', * @constructor lastName : 'bar' * @param {string} firstName }); * @param {string} lastName */ // Create a user from the model. function User(firstName, var user = User.createFromUserModel(data); lastName) { document.write(user.fullName); /** * @type {string} */ this.fullName = firstName + ' ' + lastName; }
  • 41. 良好的代碼風格 可讀性 / 可維護性 / 可用性 Developer, IDE, Compiler, JSDocBuilder
  • 46. JavaScript Everywhere PS3 . iPhone . Android ChromeOS . WebOS
  • 47. JavaScript Everything Mobile App . Game . RIA