zoukankan      html  css  js  c++  java
  • js继承之构造继承和组合继承

    //js继承之借用构造函数
    			//为了解决原型中包含引用类型值所带来的问题,我们用借用构造函数
    			function Father(){
    				this.colors = ["red" , "blue" , "yellow"];
    			}
    			
    			function Son(){
    				//继承了Father
    				Father.call(this);
    			}
    			
    			var instance1 = new Son();
    			instance1.colors.push("black");			
    			console.log(instance1.colors);
    			
    			var instance2 = new Son();
    			console.log(instance2.colors);
    			//在Son的实例对象上执行Father()函数中定义的所有对象初始化代码
    			
    			//1、传递参数
    			var Father = function(name){
    				this.name = name;
    			}
    			
    			var Son = function(age){
    				Father.call(this , "宝清老窖");
    				this.age = age;
    			}
    			
    			var instance = new Son(30);
    			console.log(instance);
    			//2、构造偶函数的问题
    			//如果仅仅是借用构造函数,那么也将无法避免构造函数模式存在的问题
    			//方法都是在构造偶函数中定义的,因此函数服用就无从谈起了。
    			//而且在Father类的原型中定义的方法,对自雷对象是不可见的
    			//结果所有类型都只能使用构造函数模式
    			//所以很少单独使用借用构造函数
    			
    			//-------------------------------------------
    			
    			//js继承之组合继承
    			//组合继承也叫伪经典继承
    			//原型链+借用构造
    			var Father = function(name){
    				this.name = name;
    				this.colors = ['red' , 'yellow' , 'green'];
    			}
    			
    			Father.prototype.sayName = function(){
    				console.log(this.name);
    			}
    			
    			var Son = function(name , age){
    				//继承属性
    				Father.call(this , name);
    				this.age = age;
    			}
    			//继承方法
    			Son.prototype = new Father();
    			Object.defineProperty(Son.prototype , 'constructor' , {
    				enumerable: false,
    				value: Son
    			});
    			
    			Son.prototype.sayAge = function(){
    				console.log(this.age);
    			}
    			
    			var son1 = new Son('宝清老窖' , 20);
    			son1.colors.push('black');
    			console.log(son1);
    			console.log(son1.colors);
    			son1.sayName()
    			son1.sayAge()
    			var son2 = new Son('金宝清' , 29);
    			console.log(son2);
    			console.log(son2.colors);
    			son2.sayName()
    			son2.sayAge()
    			//js中最常用的继承模式
    

      

  • 相关阅读:
    ubuntu 下安装memcache 以及php扩展
    js控制页面显示和表单提交
    phpcms--使用添加php原生支持
    phpcms v9 升级视频云问题推荐位不能添加
    phpcms—— 内容中的附件调用和添加远程地址的调用
    phpcms--模型管理,推荐位管理,类别管理
    linux shell 编程
    css中的定位和框模型问题
    php生成静态文件
    打印机问题win7 和xp
  • 原文地址:https://www.cnblogs.com/xudy/p/5433762.html
Copyright © 2011-2022 走看看