您的位置:首页 > 其它

原型

2015-10-28 21:55 204 查看
 原型

    JS中每一个函数都是对象,对象都拥有一个属性prototype,即原型对象,属性也是一个对象,拥有constructor属性,constructor属性指向构建函数的本身。

        function Fn(){
            
        }
        Fn.prototype.arr[1,2,3];        
                                                       //这里给Fn构建函数添加了一个属性:arr。定义了原型属性后,构造函数创建的对象可以继承原始属性并共享。
        var f1 = new Fn();
        var f2 = new Fn();
        console.log(f1.arr)
        console.log(f2.arr)                            // 因为在Fn这个构建函数下创建的两个对象f1,f2能够继承并共享原始属性或方法,所以这里的返回值都是[1,2,3];
        f1.arr[0] = 4;
        console.log(f1.arr)
        console.log(f2.arr)                     // 这里给f1的arr中的值进行了修改,修改的是 Fn.prototype.arr中的值,因此f2也会继承其属性值,两个返回结果都是[4,2,3]
        f1.arr = [4,2,3]
        console.log(f1.arr)
        console.log(f2.arr)                             // 这里是给f1添加了一个属性arr,f2不能共享和继承,所以这里返回值分别为[4,2,3]/[1,2,3]

                                           //构造函数中每个对象都有单独的属性;
                                             原型中的每个对象都共享原型的属性。        
        f1.__proto__.arr === Fn.prototype.arr                                 // 每个对象都能通过属性proto指向构建他的函数的prototype

-    原型继承和原型链

        function A(name,age){
            this.name = name;
            this.age = age;                                         //构造函数A本身定义两个属性name和age
        }
        A.proptotype.sayName = function(){                    // 给A添加了一个属性(方法)sayName
            console.log(this.name)  
        }
        function B(name,age,sex){
            A.call(this,name,age)                     //这里this是指向函数A,B通过call方法继承了A的属性
            this.sex = sex;                               // 这里this 指向B
        }
        B.protpotype = new A();                      // 这里就是原型继承,使B的原型属性指向了A的属性
        var c = new B("kobe",30,男)
        console.log(stu.name, stu.age, stu.sex);
        stu.sayName();                                                //返回结果是 kobe,30,男  kobe。
        
        原型链:先在基本属性中寻找,再通过__proto__的方法向上级继续寻找。
        
        Object.prototype.name = 3;       
        function Grandfather(){
           this.name = "1";
           this.sayName = function () {

            }
        }

           function Father() {
            this.name = 2;
        }
           Father.prototype = new Grandfather();
        function Child() {

        }

        Child.prototype = new Father();

         var c1 = new Child();

          console.log(c1.name);

        //输出为2。c1是Child构建出来的对象,所以会在函数Child中需找属性name,Child本身中并没有name属性,但是Child通过Child.prototype = new Father()语句将原型属性指向了Father函数,所以会继续在Father中寻找,所以取值为2.如果这里Father属性中没有name,则通过Father.prototype = new Grandfather()再继续在Grandfather中寻找,如果也没有,则输出3,因为在整个原型链中没有找到对应显性属性时,就会输出Object的name属性值,此时Object为所有对象的父类。

        
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: