对象生成
1. 使用闭包方式模拟对象生成
// Use closure to simulate class
function CalculatorClosure (name){
var id = 1;
return {
plus : function(a, b){
return a + b;
},
minus : function(a, b){
return a - b;
},
setName : function(_name){
name = _name;
},
getName : function(){
return name;
},
getId : function(){
return id;
}
}
}
//Run the example:
var obj = CalculatorClosure("Name");
console.log(obj.getName());
console.log(obj.minus(2,6));
代码中可以看到,是通过调用函数返回一个对象。该被返回的对象里有对应属性名的函数,这些函数类似于面向对象语言中pulic作用范围的函数。
2. 一般生成对象
function CalculatorNormal (name){
this.id = 2;
var battery = 0.99;
function getDisplayBattery(){
return battery * 100 + "%";
}
this.plus = function(a, b){
return a + b;
}
this.minus = function(a, b){
return a - b;
}
this.setName = function(_name){
name = _name;
}
this.getName = function(){
return name;
}
this.getId = function(){
return this.id;
}
this.getBattery = function(display = false){
if(false == display){
return battery;
}else{
return getDisplayBattery();
}
}
}
//Run example
var obj = new CalculatorNormal("Air");
console.log(obj.getBattery());
console.log(obj.getId());
console.log(obj.getBattery(true));
这里凡是带this.的成员变量与函数都是public作用域,反之,则是private作用域。
3. 通过prototype来实现对象的生成
// class implemented with prototype
function CalculatorPrototype (name){
this.id = 2;
this.name = name;
}
(function(){
this.plus = function(a, b){
return a + b;
}
this.minus = function(a, b){
return a - b;
}
this.setName = function(_name){
this.name = _name;
}
this.getName = function(){
return this.name;
}
this.getId = function(){
return id;
}
}).call(CalculatorPrototype.prototype);
因为每次new一个对象时,可以复用成员函数,这里建议采用prototype方式实现对象的生成,可以减少function建立的开销。
继承
// class inheritance
function Employee() {
this.name = "";
this.department = "general";
this.sayHello = function(){
return "Hello!";
}
}
function Manager() {
Employee.call(this);
this.reports = ["a", "b", "c"];
}
Manager.prototype = Object.create(Employee.prototype);
Manager.prototype.constructor = Manager;
//Run example
var obj = new Manager();
console.log(obj.sayHello());
console.log(obj instanceof Manager);
console.log(obj instanceof Employee);
以上的例子,采用this定义的成员作用域都为public, 反之,由于闭包特性,则为private作用域,可被所有该方法里所有成员可见,但对闭包外不可见。
由于JS是一种灵活的语言,以上只是简要概述几种面向对象编程的实现方法。若要深入了解Javascript面相对象编程方法,可以访问https://developer.mozilla.org/en-US/docs/Web/JavaScript。