Javascript Design Patterns - Js Class

本文讲解了JavaScript中如何使用函数模拟类的概念,并介绍了通过构造函数和原型对象来创建实例及方法,强调了将方法置于原型上的性能优势。

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

 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值