博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
Javascript Design Patterns - Js Class
阅读量:7090 次
发布时间:2019-06-28

本文共 1221 字,大约阅读时间需要 4 分钟。

JavaScript is a class-less language, however classes can be simulated using functions. 

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 classvar 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)

 

 

转载于:https://www.cnblogs.com/davidgu/p/3294687.html

你可能感兴趣的文章
从Exchange 通往Office 365系列(十五)配置ADRMS与Exchange结合
查看>>
好用的软件之Xmind
查看>>
elasticsearch rpm安装以及配置修改
查看>>
Javascript获取元素的坐标
查看>>
使用 lsof 查找打开的文件
查看>>
Linkwedo 提升信息在决策中的力量
查看>>
雨林木风GhostXP_SP3装机版YN11.6_2011.06更新
查看>>
我的友情链接
查看>>
vim8.0 不能用鼠标
查看>>
OpenGL进阶(十) - obj文件的导入
查看>>
剑指XX游戏(八) - 腾讯2013校园招聘技术类笔试题详解
查看>>
docker 添加基础命令
查看>>
arm7上搭建boa并进行测试cgi+html
查看>>
iptables/netfiles基本使用
查看>>
angularJS拍照
查看>>
HTML5接入与OC交互
查看>>
Nagios监控基本配置(二)
查看>>
C# 读写文件
查看>>
nginx网站防盗链
查看>>
品牌整合营销传播应该这样走
查看>>