zoukankan      html  css  js  c++  java
  • Javascript 继承模式

    在面向对象的JavaScript开发中使用继承可以提高代码重用性,javascript有多重方式可以实现继承,考虑代码的可维护性在项目中应该保持代码风格的一致性,下面是JavaScript中继承的实现方式之一:

    辅助对象:

    var global = window;
    
    (function(ns,undefined){
    		  
    	//辅助对象:
    	var Class = {
    		
    		extends: function(SubClass, SuperClass){
    			
    			var F = function() {};
    			F.prototype = SuperClass.prototype;
    			SubClass.prototype = new F();
    			SubClass.prototype.constructor = SubClass;
    			
    			SubClass.base = SuperClass.prototype;
    			if(SuperClass.prototype.constructor == Object.prototype.constructor) {
    				SuperClass.prototype.constructor = SuperClass;
    			}
    		  
    		}
    	}
    	
    	global.Class = Class;
    }(global, undefined));
    

     继承模式:

    function Person(name){
    	this.name = name;
    }
    
    Person.prototype = {
    	
    	getName: function(){
    		console.log("Person.prototype.getName")
    	},
    	
    	say: function(){
    		console.log("Person.prototype.say")
    	}
    };
    
    function Employee(title, name){
    	Employee.base.constructor.call(this, name);
    	this.title = title;
    }
    Class.extends(Employee, Person);
    
    //重写person.prototype.say
    Employee.prototype.say = function(){
    	Employee.base.say.call(this);//调用父类方法
    	console.log("Employee.prototype.say");
    };
    
    Employee.prototype.getTitle = function(){
    	console.log("Employee.prototype.getTitle")
    };
    

     调用演示:

    var e = new Employee("前端", "jser");
    console.log(e.name)
    console.log(e.title)
    e.getName() 
    e.getTitle()
    e.say()
    
    //运行结果:
    //jser
    //前端
    //Person.prototype.getName
    //Employee.prototype.getTitle
    //Person.prototype.say
    //Employee.prototype.say
    
  • 相关阅读:
    实用分页小方法
    Android:Handler实现异步处理功能
    Android--sharepreference总结
    安卓 如何向数据库传值
    Activity 之间的传值
    Android 双击返回键退出程序 实现
    HttpUtitlity.UrlEncode
    android 如何设置背景的透明度
    比较Date时间先后
    iOS 判断字符串中含有某个字符串 rangeOfString
  • 原文地址:https://www.cnblogs.com/rentj1/p/2853154.html
Copyright © 2011-2022 走看看