zoukankan      html  css  js  c++  java
  • 面向对象--构造函数

    一、生成实例对象的原始模式

    var cat = {
    		name: '',
    		color: ''
    	}
    
    	var cat1 = {};
    	cat1.name ='大毛';
    	cat1.color = '黄色';
    
    	var cat2 = {};
    	cat2.name = '二毛';
    	cat2.color = '黑色';
    

    二、解决代码重复 写一个函数

    function Cat (name, color){
    		return {
    			name: name,
    			color: color
    		}
    	}
    
    	var Cat1 = Cat('三毛', '红色');
    	var Cat2 = Cat('四毛', '绿色');
    

    三、看不出同一个原型,用构造函数

    function CatNew (name, color ){
    		this.name = name;
    		this.color = color;
    	}
    	var cat3 = new CatNew('六毛', '灰色');
    	var cat4 = new CatNew('七毛', '白色');
    

    注: 所有实例拥有相同属性和方法时,用prototype模式

      原因:每创建一个实例就需要重复一次代码,占用内存,降低性能 

    未使用prototype:

    function CatQ( name, color ){
    		this.name = name;
    		this.color = color;
    		this.type = '猫科动物';
    		this.eat = function () {
    			console.log('吃老鼠');
    		}
    	}
    
    	var cat5 = new CatQ('老五', '彩色');
    	var cat6 = new CatQ('老六','黑白');
    

    使用prototype:

    function Catq (name, color) {
    		this.name = name;
    		this.color = color;
    	}
    	Catq.prototype.type = "我是猫科动物";
    	Catq.prototype.eat = function () {
    		console.log('我想吃老鼠');
    	}
    
    	var cat7 = new Catq('老七', '灰色');
    	var cat8 = new Catq('老八',"白色");
    	for(var prop in cat7) {
    		console.log(prop);//属性的遍历
    	}
    

    使用prototyope模式:

    所有实例对象的eat方法和type属性都是同一个内存地址   指向prototype 对象  

      

      

  • 相关阅读:
    JAVA日报
    JAVA日报
    JAVA日报
    论文爬取(四)
    论文爬取(三)
    论文爬取(二)
    剑指 Offer 59
    剑指 Offer 58
    剑指 Offer 58
    剑指 Offer 57
  • 原文地址:https://www.cnblogs.com/yigexiaojiangshi/p/7404871.html
Copyright © 2011-2022 走看看