javascript object oriented (OOP) Detailed

Object-oriented overview:
on an abstract code, external unified call interface provides programming ideas.
Object : summary is unordered collection of properties and methods of
prototype-based object-oriented: prototype-based object-oriented way, the object is constructors rely prototype constructed using the
Object is the parent is the root of javascript
prototype: each function will have a prototype property, this property is a memory address pointing to the object, which stores the memory address of an object
instanceof: detecting whether or not the object belonging to a particular instance of a class

Object constructor:
var obj = new new Function (var1, var2, ..., FunctionBody ());
Note: low efficiency of objects constructed in this manner, the object created in this way is called the function object, objects other general call
instance:

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

6 Ways to create objects

    // 第一种  字面量方式创建对象
    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)
Published 25 original articles · won praise 0 · Views 638

Guess you like

Origin blog.csdn.net/JamesHKK/article/details/104550704