javascritpt 原型链

// 基类
var BaseCalculator = function(){
	this.decimalDigits = 2;
};

// public
BaseCalculator.prototype.add = function(x, y) {
	return x + y;
}

// public
BaseCalculator.prototype.subtract = function(x, y) {
	return x - y;
}

// 子类
var Calculator = function() {
	this.tax = 5;
};

// 覆盖重写
Calculator.prototype.add = function(x, y) {
	return x + y + this.tax;
}

// 实例继承
Calculator.prototype = new BaseCalculator();
var calc = new Calculator();
console.log(calc.add(1,1));
console.log(calc.decimalDigits);

/* 原型继承,不让子类访问基类的属性
Calculator.prototype = BaseCalculator.prototype;

var calc = new Calculator();
console.log(calc.add(1,1));
console.log(calc.decimalDigits);// 无法访问
*/

// 原型链遍历从自身属性到原型链,从下向上遍历,到Object.prototype 结束。

Object.prototype.bar = 1;
var foo = {moo:2};

for(var i in foo) {
	console.log(i);
}

// foo bar

for(var i in foo) {
	if(foo.hasOwnProperty(i)) {
		console.log(i);
	}
}

// moo

javascritpt 原型链,布布扣,bubuko.com

javascritpt 原型链

上一篇:Java 扑克发牌算法实现


下一篇:Python 提取新浪微博转载微博的用户名