JS原型继承踩坑指南

JS原型继承踩坑指南

/**
 * JS 原型继承
 * author: sipeng
 * website: www.sipeng.net
 */
var Parent = function(){
	/**
	 * 成员属性
	 * 在继承之后该属性将独立于子类中
	 */
	this.arr = [];
};
/**
 * 静态方法
 * 在继承之后该属性将在所有子类中共享该属性
 */
Parent.prototype.array = [];


var Child = function(){};
var Children = function(){};

//继承
Child.prototype = new Parent();
Children.prototype = new Parent();

Child.prototype.plus = function(){
	this.arr.push('child');
	this.array.push('child-array');
	console.log(this.arr , this.array);
}

Children.prototype.plus = function(){
	this.arr.push('child');
	this.array.push('child-array');
	console.log(this.arr , this.array);
}

var $Child = new Child();
var $Children = new Children();

$Child.plus(); // 输出 => [ 'child' ] [ 'child-array' ]
$Children.plus(); // 输出 => [ 'child' ] [ 'child-array', 'child-array' ]



验证码: 看不清楚?