zoukankan      html  css  js  c++  java
  • 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
    

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

  • 相关阅读:
    大二暑期周总结(四)
    大二暑期周总结(三)
    寒假十七
    寒假十六
    寒假十五
    寒假十四
    寒假十三
    寒假十二
    寒假十一
    寒假十
  • 原文地址:https://www.cnblogs.com/mengfanrong/p/4791330.html
Copyright © 2011-2022 走看看