創(chuàng)建對(duì)象

工廠(chǎng)方式

function Car(name, color){
        let car = new Object();// 每一次通過(guò)工廠(chǎng)方法去創(chuàng)建一個(gè)對(duì)象
        car.name = name;
        car.color = color;
        car.say = function(){
          console.log(this.color);
        }
        return car;
      }
      var c1 = Car('xp', 'red');
      var c2 = Car('BMW', 'white');
      c1.say ();
      c2.say ();

缺點(diǎn):
1.無(wú)法確定對(duì)象的類(lèi)型(因?yàn)槎际荗bject)。
2.創(chuàng)建的多個(gè)對(duì)象之間沒(méi)有關(guān)聯(lián)。
3.這個(gè)對(duì)象的屬性name和方法say 都必須重新創(chuàng)建一次,浪費(fèi)內(nèi)存

構(gòu)造函數(shù)

function Car(name, color){
        this.name = name;
        this.color = color;
        this.say = function(){
          alert(name);
        }
      }

      let car = new Car('kiwi', 'red');
      car.say();

缺點(diǎn):
1.多個(gè)實(shí)例重復(fù)創(chuàng)建方法,無(wú)法共享。
2.多個(gè)實(shí)例都有say 方法,但均不是同一個(gè)Function的實(shí)例。

原型

    function Car(){

      }

      Car.prototype.name = 'kiwi';
      Car.prototype.color = 'red';
      Car.prototype.list = new Array('a', 'b');
      Car.prototype.say = function(){
        console.log(this.name+'---------------------');
      }
      let car = new Car();
      car.say();
      car.name = 'jojo';
      car.list.push('c');
      console.log(car.name);// jojo
      console.log(car.list);// 數(shù)組的引用值,Car的兩個(gè)對(duì)象指向的都是同一個(gè)數(shù)組
      car.say();// a,b,c

      let car2 = new Car();
      car2.say();
      console.log(car2.name);// kiwi
      console.log(car2.list);//a,b,c

缺點(diǎn):
1.無(wú)法傳入?yún)?shù),不能初始化屬性值。
2.如果包含引用類(lèi)型的值時(shí),改變其中一個(gè)實(shí)例的值,則會(huì)在所有實(shí)例中體現(xiàn)。

混合原型,構(gòu)造函數(shù)

// 構(gòu)造函數(shù)
      function Car(name, color){
        this.name = name;
        this.color = color;
        this.list = new Array('a', 'b');
      }
      // 原型
      Car.prototype.say = function(){
        console.log(this.color+'---------------------');
      }
      let car = new Car('kiwi', 'red');
      car.list.push('c');
      console.log(car.list);// a, b, c

      let car2 = new Car('kiwi', 'red');
      console.log(car2.list);// a, b

優(yōu)點(diǎn): 這種是目前用的最多的創(chuàng)建類(lèi)和對(duì)象的方式, 將方法和屬性用不同的方式封裝.
構(gòu)造函數(shù)共享實(shí)例屬性,原型共享方法??蓚鬟f參數(shù),初始化屬性值。

動(dòng)態(tài)原型,構(gòu)造函數(shù)

// 構(gòu)造函數(shù)
      function Car(name, color){
        this.name = name;
        this.color = color;
        this.list = new Array('a', 'b');
        // 屬性的方法不會(huì)被重復(fù)創(chuàng)建, 只執(zhí)行一次
        if (typeof this.say != 'function'){
          Car.prototype.say = function(){
            console.log(this.name);
          }
        }
      }
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀(guān)點(diǎn),簡(jiǎn)書(shū)系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容