首頁 > web前端 > js教程 > 主體

詳細講解JS重寫原型對象

亚连
發布: 2018-05-17 10:10:36
原創
2035 人瀏覽過

JS原型的修改與重寫

對於js原型的修改有兩種方式:

1. 在原有的原型物件上新增屬性與方法:12

function Person(){
            }
            Person.prototype.name="Mike";
            Person.prototype.sayName=function(){
                console.log(this.name);
            }            var person=
new
 Person();
            person.sayName(); //Mike123456789
登入後複製

2. 重寫或說是覆寫原型物件:12

  function Person(){
            }
            Person.prototype={                "name":"Mike",
                sayName:function(){
                    console.log(this.name);
                }
            }            var person=new Person();
            person.sayName(); //Mike1234567891011
登入後複製

接下來我們來看一個問題:(這個問題也解釋了直接在原型物件上添加屬性和方法和重寫或覆寫原型物件是有區別的。)12
           

function Person(){
            }            function Animal(){
            }            var person=new Person();            var animal=new Animal();
            Person.prototype={                "name":"Mike",
                sayName:function(){
                    console.log(this.name);
                }
            }
            Animal.prototype.name="animal";
            Animal.prototype.sayName=function(){
                console.log(this.name);
            }
            person.sayName(); //error person.sayName is not a function
            animal.sayName();//animal1234567891011121314151617181920
 分析:12
            function Person(){
            }            function Animal(){
            }            var person=new Person();            var animal=new Animal();
            console.log(person.
proto
===Person.prototype); //true
            console.log(animal.proto===Animal.prototype); //true
            Person.prototype={                "name":"Mike",
                sayName:function(){
                    console.log(this.name);
                }
            }
            Animal.prototype.name="animal";
            Animal.prototype.sayName=function(){
                console.log(this.name);
            }
            console.log(person.proto===Person.prototype); //false
            console.log(animal.proto===Animal.prototype); //true
            person.sayName(); //error person.sayName is not a function
            animal.sayName();//animal
登入後複製

上面是我整理給大家的JS重寫原型對象,希望未來對大家有幫助。

相關文章:

js方法的重寫和重載的技巧詳解

重點分析JavaScript重寫alert ()方法的技巧

js繼承中的方法重寫重點解說

以上是詳細講解JS重寫原型對象的詳細內容。更多資訊請關注PHP中文網其他相關文章!

相關標籤:
來源:php.cn
本網站聲明
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn
最新問題
熱門教學
更多>
最新下載
更多>
網站特效
網站源碼
網站素材
前端模板
關於我們 免責聲明 Sitemap
PHP中文網:公益線上PHP培訓,幫助PHP學習者快速成長!