Prototype function js

js a constructor for each attribute has a prototype, prototype point to an object, the object's properties and methods that will be inherited instance constructors, and therefore, requires some shared properties and methods can be written in function prototyping in

1 can add properties and methods to the constructor with inheritable prototype property, attribute points to note constructor function prototype object is located

    <script>
        function Person(){
        }
        Person.prototype = {
            constructor: Person,
            name: 'xxx',
            age: 22,
            sayName: function(){
                console.log(this.name);
            }
        }
        var p = new Person();
        p.sayName();//'xxx'
        console.log(p.age);//22
    </script>

2 a property with the same name exists in the constructor and in the prototype object, an instance constructor constructor uses of this property, similar to the priority: Example> Constructor> Prototype

    <Script>
         function the Person () {
             the this .age = 233; // assigns the instance when creating an instance attribute 
        } 
        Person.prototype = { 
            constructor: the Person, 
            name: 'XXX' , 
            Age: 22 is , 
            sayName: function () { 
                the console.log ( the this .name); 
            } 
        } 
        var P = new new the Person (); 
        the console.log (p.age); // 233 
        p.age = 333 ; 
        the console.log (p.age);//333
    </script>

3 prototype inheritance

    <Script>
         function the Person () {
             the this .age = 233; // assigns the instance when creating an instance attribute 
        } 
        Person.prototype = { 
            constructor: the Person, 
            name: 'XXX' , 
            Age: 22 is , 
            sayName: function () { 
                the console.log ( the this .name); 
            } 
        } 
        var P = new new the Person (); 
        the console.log (p.age); // 233 
        p.age = 333; 
        the console.log (p.age);//333
        function Student(){

        }
        Student.prototype = new Person();//继承
        var s = new Student();
        console.log(s.name);//'xxx'
        s.name = 'qqq';
        console.log(s.name);//'qqq'
    </script>
View Code

 

Guess you like

Origin www.cnblogs.com/Zxq-zn/p/11609903.html