Javascript Design Patterns - Js Class
2013-09-01 16:34
302 查看
JavaScript is a class-less language, however classes can be simulated using functions.
eg:
We can then instantiate the object using the Car constructor we defined above like this:
另一个例子
上述关于类函数的做法性能不佳,原因如下:
any time you call new Person() a new function is created in memory.
This is obviously inefficient, because the say() method doesn’t change from one instance to the next.
(每次new对象的时候会在内存中新建一个函数)
The better option is to add the method to the prototype of Person
(比较好的方法是把方法增加到Person对象的prototype)
just remember that reusable members, such as methods, should go to the prototype
(关于JS类必须要记住的是,可重用的成员,例如方法必须放到对象的prototype)
eg:
// A car 'class' function Car(model) { this.model = model; this.color = 'silver'; this.year = '2012'; this.getInfo = function () { return this.model + ' ' + this.year; } }
We can then instantiate the object using the Car constructor we defined above like this:
var myCar = new Car('ford'); myCar.year = '2010'; console.log(myCar.getInfo());
另一个例子
var Person = function (name) { this.name = name; this.say = function () { return "I am " + this.name; }; }; // use the class var adam = new Person("Adam"); adam.say(); // "I am Adam"
上述关于类函数的做法性能不佳,原因如下:
any time you call new Person() a new function is created in memory.
This is obviously inefficient, because the say() method doesn’t change from one instance to the next.
(每次new对象的时候会在内存中新建一个函数)
The better option is to add the method to the prototype of Person
(比较好的方法是把方法增加到Person对象的prototype)
Person.prototype.say = function () { return "I am " + this.name; };
just remember that reusable members, such as methods, should go to the prototype
(关于JS类必须要记住的是,可重用的成员,例如方法必须放到对象的prototype)
相关文章推荐
- 【读书笔记】《Node.js Design Patterns》前言
- Pro Javascript Design Patterns勘误Errata汇总(持续更新中)
- 【读书】《Node.js Design Patterns》1.1——Node.js哲学
- <Learning JavaScript Design Patterns>
- javascript getElementsByClassName 和js取地址栏参数
- JS 系列一: Javascript 定义类(class)的三种方法
- 给 Javascript 加上面向对象的属性:Class.js
- Node.js Design Patterns--3. Coding with Streams
- Learning JavaScript Design Patterns The Singleton Pattern
- JavaScript 实现命名空间(namespace)的最佳方案——兼容主流的定义类(class)的方法,兼容所有浏览器,支持用JSDuck生成文档
- [必读免费新电子书]:JavaScript和jQuery基本设计模式(Essential JavaScript & jQuery Design Patterns For Beginners) 最后编辑:2010-11-16 18:15
- Javascript Module pattern template. Shows a class with a constructor and public/private methods/properties. Also shows compatibility with CommonJS(eg Node.JS) and AMD (eg requireJS) as well as in a br
- Learning JavaScript Design Patterns The Constructor Pattern
- Pro JavaScript Design Patterns
- Javascript图片播放类ImageSlide.iclass.js
- Design Patterns in iOS — Class Clusters
- 【HTML/JS】Javascript定义类(class)的三种方法
- Learning JavaScript Design Patterns The Observer Pattern
- JS基础篇--如何用JavaScript判断dom是否有存在某class的值?
- 省市县 三级 四级联动Javascript JQ 插件PCASClass.js