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  阅读(265)  评论(0编辑  收藏  举报