zoukankan      html  css  js  c++  java
  • js继承的几种方式

        要了解js继承,必定先要去了解原型链,为何呢?因为原型链是作为实现继承的主要方法。

      以下几点一定要谨记:那就是什么是构造函数、什么是原型、什么是实例、以及他们之间的关系?

      继承:利用原型让一个引用类型继承另一个引用类型的属性和方法

      每个构造函数都有一个原型对象:Person.prototype(prototype是指向原型对象的指针)

      原型对象都包含一个指向构造函数的指针:Person.prototype.constructor = Person

      实例都包含一个指向原型对象的内部指针:var a = new Person();a._proto_ = Person.prototype

      

    通过原型链实现继承

        function SuperType(){
            this.colors = ["red","blue","green"];
        }
    
        function SubType(){}
    
        SubType.prototype = new SuperType();
    
        var instance = new SubType();
        instance.colors.push("white");
        console.log(instance.colors);  //"red,blue,green,white"
    
        var instance2 = new SubType();
        console.log(instance2.colors); //"red,blue,green,white"
    

      

    借用构造函数

        function SuperType(name){
            this.name = name;
        }
        function SubType(){
            SuperType.call(this,"Lucy");
            this.age = 20;
        }
        var instance = new SubType();
        console.log(instance.name);  //Lucy
        console.log(instance.age);  //20
    

      

    组合继承

      组合继承也叫作伪经典继承,指的是将原型链和借用构造函数的技术组合在一起的继承模式,精髓是使用原型链实现对原型属性和方法的继承,通过借用构造函数来实现对实例属性的继承。

        function SuperType(name){
            this.name = name;
            this.colors = ["red","blue","green"];
        }
        SuperType.prototype.sayName = function(){
            console.log(this.name);
        }
        function SubType(name,age){
            SuperType.call(this,name);
            this.age = age;
        }
        SubType.prototype = new SuperType();
        SubType.prototype.sayAge = function(){
            console.log(this.age);
        }
    
        var instance = new SubType("Lucy",20);
        instance.colors.push("white");
        console.log(instance.colors);  //"red,blue,green,white"
        instance.sayName();   //Lucy
        instance.sayAge();    //20
    
        var instance2 = new SubType("Tom",28);
        console.log(instance2.colors);  //"red,blue,green"
        instance2.sayName();   //Tom
        instance2.sayAge();  //28
    

      

  • 相关阅读:
    ng2-timesheet, 一个timesheet.js的angular2复制版
    Angular 2 + Electron 开发web和桌面应用
    Xamarin.Forms.Platform.Perspex, Xamarin Forms 的 Perspex(号称下一代WPF) 实现
    Visual Studio Xamarin编译Android项目出错的解决办法
    Salesforce + AngularJS + Bootstrap
    NativeScript 也能开发桌面应用 (nativescript-dotnet-runtime)
    iOS集成丁香园DXY OAuth 登陆 swift代码示例
    WinObjC?这是什么鬼?
    如何禁用Marlin温度保护
    React Native也正式发布了
  • 原文地址:https://www.cnblogs.com/wanliyuan/p/5688755.html
Copyright © 2011-2022 走看看