• 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
    
  • 相关阅读:
    任天堂确认账户被黑客入侵:开启双重验证是关键,会更加安全
    受疫情影响!美国大量科技初创企业要挨饿或倒闭
    泰国的IPv6功能已从约2%增至30%,部署率位于全球5名
    vue钩子函数
    vue自定义全局指令directive和局部指令directives
    vue自定义按键修饰符
    字符串padStart、padEnd填充
    vue过滤器
    vue指令v-if和v-show
    vue指令v-for和key属性
  • 原文地址:https://www.cnblogs.com/rentj1/p/2853154.html
Copyright © 2020-2023  润新知