Javascript 工厂设计模式及继承与封装

学习了一些设计模式,写了个优化版的工厂模式,顺便把私有属性,自有的公共属性,可继承的公共属性都写在例子里了。

参考:
http://www.cnblogs.com/Darren_code/archive/2011/08/31/JavascripDesignPatterns.html 
http://blog.csdn.net/benbon/article/details/1871720

var Father = function() {
		this.age = 50;
		this.fatherName = 'Peter';
		this.sayYes = function() {
		// reuse function
			alert('yes');
		};
		var self = this;
		this.sayFatherName = function() {
		// reuse method
			alert(self.fatherName);
		};

	};

	Father.prototype = {
		saySonName : function() {
		// interface
			throw new Error('too bad, you should redefine saySonName by yourself!');
		}
	};

// when excute son directly, the father will be called;
var son = function(sonName){
	this.sonName = sonName || 'anonymous';
};

son.prototype = new Father();

// rewite the constructor with son, not father, make it cool
son.prototype.constructor = son;

//define the interface of son.prototype.saySonName
son.sonName = 'Jerry';
son.saySonName = function(){
	alert(this.sonName);
}

// call son private method
// will alert 'Jerry'
son.saySonName();

// rewrite public method
son.prototype.saySonName = function(){
	alert('I\'m ' + this.sonName);
}
var inst = new son('Paul');

inst.saySonName();

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.