zoukankan      html  css  js  c++  java
  • JavaScript的创建对象和继承

    创建对象

    1. 字面量创建
      var obj = {}
    2. Object类创建
      var obj = new Object()
    3. 组合构造函数模式(组合构造)
      function Car(color, passengers, brand){
          this.color = color;
          this.passengers = passengers;
          this.brand = brand;
          }
      }
      Car.prototype = {
      outBrand: function () { console.log(this.brand) }
      }
      var car1 = new Car('red', ['a','b'], 'benz'); var car2 = new Car('black', ['c','d'], 'BMW'); console.log(car1 instanceof Object); //true console.log(car1 instanceof Car); //true console.log(car2 instanceof Object); //true console.log(car2 instanceof Car); //true

      构造函数模式能够很好的使用 instanceof 进行对象的识别,Objcet对象是所有对象的顶层对象类,所有的对象都会继承他。对对象进行操作的各类方法就存放在Object对象里面。

        这种方式,所有对象实例都可以共享原型对象上的方法,能够最大程度节省内存(即不是构造函数模式),同时也向构造函数提供了传递参数的功能(即不是原型模式)。


    js继承(寄生组合继承)

    function Animal(){}

    Animal.prototype = {

      constructor:Animal,

      eat: function (){}

    }

    function Cat () {

      Animal.call(this)//继承父类

    }

    Cat.prototype = Object.create(Animal.prototype)

    Cat.prototype.constructor = Cat

     关于原型及原型链https://i.cnblogs.com/posts/edit;postId=13442112

    为个人总结,不适合未接触者看。

      

  • 相关阅读:
    VMware搭建VMware ESXi 6.7
    77. Combinations
    47. Permutations II
    system design
    37. Sudoku Solver
    12月9日学习日志
    12月8日学习日志
    12月7日学习日志
    12月6日学习日志
    12月5日学习日志
  • 原文地址:https://www.cnblogs.com/joeynkay/p/13442545.html
Copyright © 2011-2022 走看看