javascript 面向对象(oop)详解

面向对象概述:
对代码的一种抽象,对外统一提供调用接口的编程思想.
对象:概括来说就是属性和方法的无序集合
基于原型的面向对象:基于原型的面向对象方式中,对象则是依靠构造器利用原型构造出来的
Object是javascript父对象 也就是根
prototype:每个函数都会有一个prototype属性,这个属性是一个对象指向内存地址,这个内存地址里面存储了一个对象
instanceof:检测这个对象是否属于某个特定类的一个实例

构造函数对象:
var obj=new Function(var1,var2,…,functionBody());
注意:这种方式构造的对象效率低,这种方式创建的对象叫做函数对象,其他的都叫普通对象
实例:

  var obj=new Function("a","b","return a+b") //构造一个函数对象
      var sun=obj(2,9)
      console.log(sun)

创建对象的6种方式

    // 第一种  字面量方式创建对象
    var obj = {
      name: "qjj",
      age: 18,
      getName: function () {
        console.log(this.name)
      }
    }
    obj.getName()

    //第二种 使用new关键字 new一个对象  new Object
    var person = new Object()
    person.name = "qjj",
      person.height = 178,
      person.getHeight = function () {
        console.log(this.height)
      }
    person.getHeight()

    //第三种 构造函数模式创建对象
    function car(color, width) {
      this.color = color
      this.width = width
      this.getCor = function () {
        console.log(this.color)
      }
    }
    var bao = new car("red", 156)
    bao.getCor()

    //第四种 工厂模式创建对象
    function musicer(longer, dancer) {
      var obj = new Object()
      obj.longer = longer
      obj.dancer = dancer
      obj.getLonger = function () {
        console.log(this.longer)
      }
      return obj
    }
    var musicer1 = musicer(1554, "胡歌")
    musicer1.getLonger()


    //第五种 原型模式创建对象

    function producter() {

    }
    // producter.prototype.color = "blue"
    // producter.prototype.height = 555
    // producter.prototype.getHeig = function () {
    //   console.log(this.color)
    // }
    producter.prototype = {
      color: "blue",
      height: 555,
      getHeig: function () {
        console.log(this.color)
      }
    }

    var producter1 = new producter()
    producter1.getHeig()



    //第六种 混合模式创建对象
    function test(color, height, width) {
      this.color = color;
      this.height = height;
      this.width = width;
      this.getInfo = function () {
        console.log(this.color, this.height, this.width)
      }
    }
    test.prototype = {
      shope: "big"
    }

    var car1 = new test("red", "100", "666")
    car1.getInfo()
    console.log(car1.shope)
发布了25 篇原创文章 · 获赞 0 · 访问量 638

猜你喜欢

转载自blog.csdn.net/JamesHKK/article/details/104550704