首頁  >  文章  >  web前端  >  詳細講解JS重寫原型對象

詳細講解JS重寫原型對象

亚连
亚连原創
2018-05-17 10:10:362036瀏覽

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中文網其他相關文章!

陳述:
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn