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

版权声明:本文博主原创文章,博客,未经同意不得转载。

posted @ 2015-09-08 13:21  mengfanrong  阅读(273)  评论(0)    收藏  举报
众安尊享e升2025版 - 底部横幅广告
尊享e升 2025版
🚀 全新升级
百万医疗险全面升级 守护健康人生
✓ 一般医疗300万
✓ 重疾600万
✓ 6年保证续保
✓ 1万免赔额
600万
最高保障
首月特惠价
低至1元起
🛡️ 立即投保