在线观看不卡亚洲电影_亚洲妓女99综合网_91青青青亚洲娱乐在线观看_日韩无码高清综合久久

鍍金池/ 問答/HTML/ 讀《js高級程序設(shè)計(jì)》問題?

讀《js高級程序設(shè)計(jì)》問題?

第六章:在創(chuàng)建對象的方式中有這樣一種動態(tài)原型模式

function Persion() {
    this.name="wyq";
    this.friends=["a", "b", "c"];
    //下面的代碼有什么意義??? 每次new一個對象的時候肯定要執(zhí)行里面的函數(shù)啊
    if(typeof this.sayName !=="function"){
        this.sayName = function () {
            console.log("friends",this.friends);
        }
    }
}

直接這樣寫不就好了嗎?

function Persion() {
    this.name="wyq";
    this.friends=["a", "b", "c"];
}
Persion.prototype = {
    sayName: function () {
        console.log("this.name", this.name);
    },
};
回答
編輯回答
心上人

一段代碼的作用要看使用環(huán)境,一個功能的實(shí)現(xiàn)可能有很多種寫法

下面的寫法是我們最常見也是最常用的,那么上面的代碼和下面的代碼有什么區(qū)別呢?

區(qū)別就是上面的代碼,sayName屬性是作用在子對象上的,而下面的代碼是作用在父對象上的

上面的代碼如果修改一下

function Persion(hasSayName) {
    //...
    if(hasSayName && typeof this.sayName !=="function"){
        //...
    }
}
var p1 = new Persion
var p2 = new Persion(true)

這樣,代碼的用意就特別清晰了

2018年4月21日 06:06
編輯回答
女流氓

其實(shí)呢,雙方的目的就是創(chuàng)建個對象后,實(shí)例擁有sayName()的能力

區(qū)別在哪里呢:
這種方式創(chuàng)建的sayName是在new Persion實(shí)例后,在實(shí)例上創(chuàng)建的

function Persion() {
    this.name="wyq";
    this.friends=["a", "b", "c"];
    //下面的代碼有什么意義??? 每次new一個對象的時候肯定要執(zhí)行里面的函數(shù)啊
    if(typeof this.sayName !=="function"){
        this.sayName = function () {
            console.log("friends",this.friends);
        }
    }
}

這種方式創(chuàng)建的sayName是在Persion構(gòu)造函數(shù)上直接創(chuàng)建的

function Persion() {
    this.name="wyq";
    this.friends=["a", "b", "c"];
}
Persion.prototype = {
    sayName: function () {
        console.log("this.name", this.name);
    },
};

總結(jié)一下:一個在實(shí)例上創(chuàng)建,一個在構(gòu)造函數(shù)上創(chuàng)建

2017年12月30日 18:26