• javascript构造函数+原形继承+作用域扩充


    目前为止我认为这是最佳的声明对象的模式,将今天学到的东西写下

    <script type="text/javascript">
    	function Constructor(obj,options){
    
    		this.selector = options.selector;
    	    this.time = options.time;
    	    this.step = options.step;
    	    this.obj = document.getElementById(obj);
    		//私有方法,将不被共享,所以此方法在各个实例中不是不相等的
    		this.fuck = function(){
    			//code here
    			alert('fuck');
    		}
    	}
    
    	//公共方法,原形继承,方法在实例中是相等的
    	Constructor.prototype.getName = function(){
    		//code here
    		alert(this.selector);
    
    	}
    	Constructor.prototype.setName = function(){
    		//code here
    		alert(this.time);
    	}
    	Constructor.prototype.getIndex = function(){
    		//code here
    		alert(this.step);
    	}
    
    
    	//call继承,通过继承可以扩充实例化后的对象的作用域,call(obj,[,arr1[,arr2[,arr3]]]);
    	//obj作为第一个参数即是this指针的指向,通过重新定义指针,可以将函数的作用域赋予继承对象中;
    	//后面的参数为可选项,以逗号分隔开。这是与apply方法区别之处;
    	function callFunc(a,b){
    	    this.a = a;
    	    this.b = b;
    	    this.c = function(){
    	    	return this.a + this.b;
    	    }
    	}
    
    	//apply继承
    	//call继承,通过继承可以扩充实例化后的对象的作用域,call(obj,[arr1,arr2,arr3]);
    	//obj作为第一个参数即是this指针的指向,通过重新定义指针,可以将函数的作用域赋予继承对象中;
    	//后面的第二个参数为可选项,以数组形式存在。这是与apply方法区别之处;
    	function applyFunc(a,b){
    		this.a = a;
    		this.b = b;
    		this.c = function(){
    		    return this.a * this.b;
    		}
    	}
    
    	//实例化一个对象Constructor1
    	var Constructor1 = new Constructor('slider',{
    		selector:'selector',
    		time:2000,
    		step:30
    	});
    	//实例化一个对象Constructor2
    	var Constructor2 = new Constructor('slider',{
    		selector:'selector',
    		time:2000,
    		step:30
    	});
    
    	console.log(Constructor1 instanceof Constructor);//true
    	console.log(Constructor2 instanceof Constructor);//true
    
    	console.log(Constructor1.fuck == Constructor2.fuck);//false
    
    
    	//call继承callFunc中作用域
    	callFunc.call(Constructor1,1,2);
    	console.log(Constructor1.c());//3
    
    	//apply继承applyFunc中作用域
    	applyFunc.apply(Constructor1,[3,2]);
    	console.log(Constructor1.c());//6
    
    </script>
    

      

  • 相关阅读:
    Cider扩展架构:AttributeTable和AttributeTableBuilder
    VS编译时自动引用Debug|Release版本的dll
    扩展Oozie
    使用正则表达式找出不包含特定字符串的条目
    重构时机和重构方法之间的对应关系
    Javascript 果然存在所谓的预编译,例证:
    程序员眼中的UML(2)克服用例图的恐惧
    Hortonworks宣布一款Hadoop数据平台
    .NET Framework 4现已支持LocalDB
    REST API用得也痛苦
  • 原文地址:https://www.cnblogs.com/bestsamcn/p/5201836.html
Copyright © 2020-2023  润新知