• 技术文章 >web前端 >js教程

    详细讲解JS重写原型对象

    亚连亚连2018-05-17 10:10:36原创1203

    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核实处理。
    专题推荐:javascript 对象 原型
    上一篇:js方法的重写和重载的技巧详解 下一篇:自己动手写 PHP MVC 框架(40节精讲/巨细/新人进阶必看)

    相关文章推荐

    • react 怎么实现按需加载• react怎么实现滚动条• 一文聊聊node文件的读写操作• Angular学习之聊聊独立组件(Standalone Component)• 浅析Angular中的Change Detection机制
    1/1

    PHP中文网