原型鏈注意點(diǎn)-P16-2019-12-06

<script>
        function Student(name, age, sex) {
            // 一般情況下對象的屬性在構(gòu)造函數(shù)中設(shè)置
            this.name = name;
            this.age = age;
            this.sex = sex;
        }
        // 一般方法在構(gòu)造函數(shù)的原型上設(shè)置prototype
        Student.prototype.writeIt = function() {
                document.write('Hello PROTOTYPE!')
                    // alert("Hello PROTOTYPE")
            }
            // 多個(gè)方法可以用以下形式寫但是要注意
        console.dir(Student.prototype);
        //注意以上代碼★★
        Student.prototype = {
            writeIt: function() {
                document.write('Hello PROTOTYPE!')
                    // alert("Hello PROTOTYPE")
            },
            eat: function() {
                log("....")
            }
        }
        //注意以下代碼★★
        console.dir(Student.prototype);

        var a = new Student();
        // a.writeIt();
        // console.log(a.constructor);
    </script>
第二種寫法.png

所引起的問題.png

當(dāng)我們訪問constructor屬性時(shí)先找本身有沒有,再找原型對象中有沒有,結(jié)果原型對象也沒有,就在找原型對象的原型對象結(jié)果找到了時(shí)object類型

image.png

怎么解決呢?

解決辦法.png
image.png
//代碼如下
 Student.prototype = {
            constructor: Student,
//再次指定該對象到底屬于哪類對象
            writeIt: function() {
                document.write('Hello PROTOTYPE!')
                    // alert("Hello PROTOTYPE")
            },
            eat: function() {
                log("....")
            }
        }
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

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

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