Javascript里的设计模式
来源:互联网 发布:cnc编程学习 编辑:程序博客网 时间:2024/05/22 02:24
不管你信不信反正js很高深,虽然平时都是getElementById,现在用了jQuery,这东西也很少用了,也就for,if或者字符串操作一下。
本文本着实用的原则,列举了几个常用的js代码写法,让自己的js看起来更优美。
更多详细:http://addyosmani.com/resources/essentialjsdesignpatterns/book/
Constructor Pattern
function Car( model, year, miles ) { this.model = model; this.year = year; this.miles = miles;}// Note here that we are using Object.prototype.newMethod rather than // Object.prototype so as to avoid redefining the prototype objectCar.prototype.toString = function () { return this.model + " has done " + this.miles + " miles";};// Usage:var civic = new Car( "Honda Civic", 2009, 20000 );var mondeo = new Car( "Ford Mondeo", 2010, 5000 );console.log( civic.toString() );console.log( mondeo.toString() );
用this声明的就相当于public的Module Pattern
var myModule = { myProperty: "someValue", // object literals can contain properties and methods. // e.g we can define a further object for module configuration: myConfig: { useCaching: true, language: "en" }, // a very basic method myMethod: function () { console.log( "Where in the world is Paul Irish today?" ); }, // output a value based on the current configuration myMethod2: function () { console.log( "Caching is:" + ( this.myConfig.useCaching ) ? "enabled" : "disabled" ); }, // override the current configuration myMethod3: function( newConfig ) { if ( typeof newConfig === "object" ) { this.myConfig = newConfig; console.log( this.myConfig.language ); } }};// Outputs: Where in the world is Paul Irish today?myModule.myMethod();// Outputs: enabledmyModule.myMethod2();// Outputs: frmyModule.myMethod3({ language: "fr", useCaching: false});
var myNamespace = (function () { var myPrivateVar, myPrivateMethod; // A private counter variable myPrivateVar = 0; // A private function which logs any arguments myPrivateMethod = function( foo ) { console.log( foo ); }; return { // A public variable myPublicVar: "foo", // A public function utilizing privates myPublicFunction: function( bar ) { // Increment our private counter myPrivateVar++; // Call our private method using bar myPrivateMethod( bar ); } };})();
- Javascript里的设计模式
- JDK里的设计模式
- JDK里的设计模式
- JDK里的设计模式
- JDK里的设计模式
- JDK里的设计模式
- JDK里的设计模式
- JDK里的设计模式
- JDK里的设计模式
- JDK里的设计模式
- JDK里的设计模式
- JDK里的设计模式
- JDK里的设计模式
- JDK里的设计模式
- JDK里的设计模式
- JDK里的设计模式
- JDK里的设计模式
- JDK里的设计模式
- helloworld驱动加强版
- LUA学习
- GridView分页数据处理,在sql存储过程中取得每页数据
- Git创建新的空分支
- JPEG编码
- Javascript里的设计模式
- SSH框架项目学习记录
- vi同时编辑多个文件
- Storyboard 的简单使用
- Performance testing shared vs. static libs
- <body>居中显示
- Oracle-CASE WHEN使用
- js关于有参函数的调用。
- Android技术积累:图片异步加载