Javascript的面相对象编程

本文详细介绍了JavaScript中面向对象编程的实现方法,包括闭包、普通生成、原型实现等,并通过实例展示了如何创建对象及其成员函数。此外,文章还讨论了继承的概念和实践,以及如何利用闭包和私有作用域来管理对象内部状态。

对象生成

   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

 

转载于:https://my.oschina.net/keepthinker/blog/689163

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值