• Prototype原型模式


    通过构造函数的弊端引出原型概念

    先看一个一只猫的构造函数

    function Cat(name,color){
        this.name = name;
        this.color = color;
        this.type = "猫科动物";
        this.eat = function(){alert("吃老鼠");};
    }
    
    var cat1 = new Cat("大毛","黄色");
    var cat2 = new Cat ("二毛","黑色");
    alert(cat1.type); // 猫科动物
    cat1.eat(); // 吃老鼠  

    表面上好像没什么问题,但是实际上这样做,有一个很大的弊端。那就是对于每一个实例对象,type属性和eat()方法都是一模一样的内容,每一次生成一个实例,都必须为重复的内容,多占用一些内存。这样既不环保,也缺乏效率。

    再看

    alert(cat1.eat == cat2.eat); //false 

    因此,为了让type属性和eat()方法在内存中只生成一次,然后所有实例都指向那个内存地址,引出了原型

    什么是原型?

    原型对象实际上就是构造函数的一个实例,和普通的实力对象没有本质上的区别。可以包含特定类型的所有实例的共享属性或者方法。这个prototype的属性值是一个对象(属性的集合),默认的只有一个叫做constructor的属性,指向这个函数本身。

    比如我们简单定义一个SuperType名字的函数,里面什么属性也没有在函数内部是这个样子的

    function SuperType(){
    }

    从上图我们看到,函数里面虽然什么都没有,但是有一个默认的prototype属性,它是一个对象,它指向的是自己的地址,而prototype这个对象本身里面又有一个属性constructor,而这个属性,又指向了函数本身,有点绕,你可以通过下面的代码做一下测试,看看效果

    alert(SuperType.prototype) //object
    alert(SuperType.prototype.constructor) //弹出函数本身function SuperType(){}   

    prototype和constructor是原型最基本的概念

    把之前的Cat构造函数修改成如下:

    function Cat(name,color){
        this.name = name;
        this.color = color;
    }
    Cat.prototype.type = "猫科动物";
    Cat.prototype.eat = function(){alert("吃老鼠")};  
    var cat1 = new Cat("大毛","黄色");
    var cat2 = new Cat("二毛","黑色");
    alert(cat1.type); // 猫科动物
    cat1.eat(); // 吃老鼠  

    这时所有实例的type属性和eat()方法,其实都是同一个内存地址指向prototype对象,因此就提高了运行效率。

    alert(cat1.eat == cat2.eat); //true

    Prototype模式的验证方法

    为了配合prototype属性,Javascript定义了一些辅助方法,帮助我们使用它。

    isPrototypeOf()    这个方法用来判断,某个proptotype对象和某个实例之间的关系。

    function Cat(name,color){
        this.name = name;
        this.color = color;
    }
    Cat.prototype.type = "猫科动物";
    Cat.prototype.eat = function(){alert("吃老鼠")};  
    var cat1 = new Cat("大毛","黄色");
    var cat2 = new Cat("二毛","黑色");
    alert(cat1.type); // 猫科动物
    cat1.eat(); // 吃老鼠  
    
    alert(Cat.prototype.isPrototypeOf(cat1)); //true
    alert(Cat.prototype.isPrototypeOf(cat2)); //true  

    hasOwnProperty()    每个实例对象都有一个hasOwnProperty()方法,用来判断某一个属性到底是本地属性,还是继承自prototype对象的属性。

    alert(cat1.hasOwnProperty("name")); // true
    alert(cat1.hasOwnProperty("type")); // false  

    in运算符   in运算符可以用来判断,某个实例是否含有某个属性,不管是不是本地属性。

    alert("name" in cat1); // true
    alert("type" in cat1); // true  

    in运算符还可以用来遍历某个对象的所有属性。

    for(var prop in cat1) { 
        alert("cat1["+prop+"]="+cat1[prop]); 
    }

    来看一下 javascript高级程序设计 书中对与原型的描述和说明

    function Person(){ }  //创建Person构造函数
    Person.prototype.name = "Nicholas";//创建共享属性name 
    Person.prototype.age = 29; //创建共享属性age 
    Person.prototype.job = "Software Engineer"; //创建共享属性job 
    Person.prototype.sayName = function(){     //创建共享函数sayName
        alert(this.name); 
    };  
    
    //分别创建了person1和person2,里面都有sayName函数,并且弹出的值都是一样
    var person1 = new Person(); 
    person1.sayName();   //"Nicholas"  
    var person2 = new Person();
    person2.sayName();   //"Nicholas"  
    alert(person1.sayName == person2.sayName);  //true   

    通过上面的图,可以看到,person1和person2,他们内部都有一个指向Person.prototype的指针,可以通过原型的isPrototype方法测试一下

    alert(Person.prototype.isPrototypeOf(person1));  //true
    alert(Person.prototype.isPrototypeOf(person2));  //true
    function User(){};
    var person3 = new User();
    alert(Person.prototype.isPrototypeOf(person3));  //false
    alert(User.prototype.isPrototypeOf(person3));  //true  

    作为类比,我们考虑下JavaScript中的数据类型 - 字符串(String)、数字(Number)、数组(Array)、对象(Object)、日期(Date)等。 我们有理由相信,在JavaScript内部这些类型都是作为构造函数来实现的,比如: // 定义数组的构造函数,作为JavaScript的一种预定义类型 function Array() { // ... }

    // 初始化数组的实例
    var arr1 = new Array(1, 56, 34, 12);
    // 但是,我们更倾向于如下的语法定义:
    var arr2 = [1, 56, 34, 12];  

    同时对数组操作的很多方法(比如concat、join、push)应该也是在prototype属性中定义的。 实际上,JavaScript所有的固有数据类型都具有只读的prototype属性(这是可以理解的:因为如果修改了这些类型的prototype属性,则哪些预定义的方法就消失了), 但是我们可以向其中添加自己的扩展方法。

     // 向JavaScript固有类型Array扩展一个获取最小值的方法
        Array.prototype.min = function() {
            var min = this[0];
            for (var i = 1; i < this.length; i++) {
                if (this[i] < min) {
                    min = this[i];
                }
            }
            return min;
        };
    
        // 在任意Array的实例上调用min方法
        console.log([1, 56, 34, 12].min());  // 1 

    注意:这里有一个陷阱,向Array的原型中添加扩展方法后,当使用for-in循环数组时,这个扩展方法也会被循环出来。 下面的代码说明这一点(假设已经向Array的原型中扩展了min方法):

        var arr = [1, 56, 34, 12];
        var total = 0;
        for (var i in arr) {
            total += parseInt(arr[i], 10);
        }
        console.log(total);   // NaN  

    解决方法:

      var arr = [1, 56, 34, 12];
        var total = 0;
        for (var i in arr) {
            if (arr.hasOwnProperty(i)) {
                total += parseInt(arr[i], 10);
            }
        }
        console.log(total);   // 103

    constructor

    constructor始终指向创建当前对象的构造函数。比如下面例子:

     // 等价于 var foo = new Array(1, 56, 34, 12);
        var arr = [1, 56, 34, 12];
        console.log(arr.constructor === Array); // true
        // 等价于 var foo = new Function();
        var Foo = function() { };
        console.log(Foo.constructor === Function); // true
        // 由构造函数实例化一个obj对象
        var obj = new Foo();
        console.log(obj.constructor === Foo); // true
    
        // 将上面两段代码合起来,就得到下面的结论
        console.log(obj.constructor.constructor === Function); // true 

    但是当constructor遇到prototype时,有趣的事情就发生了。 我们知道每个函数都有一个默认的属性prototype,而这个prototype的constructor默认指向这个函数。如下例所示:

     function Person(name) {
            this.name = name;
        };
        Person.prototype.getName = function() {
            return this.name;
        };
        var p = new Person("ZhangSan");
    
        console.log(p.constructor === Person);  // true
        console.log(Person.prototype.constructor === Person); // true
        // 将上两行代码合并就得到如下结果
        console.log(p.constructor.prototype.constructor === Person); // true  

    当时当我们重新定义函数的prototype时 (注意:和上例的区别,这里不是修改而是覆盖)constructor的行为

      function Person(name) {
            this.name = name;
        };
        Person.prototype = {
            getName: function() {
                return this.name;
            }
        };
        var p = new Person("ZhangSan");
        console.log(p.constructor === Person);  // false
        console.log(Person.prototype.constructor === Person); // false
        console.log(p.constructor.prototype.constructor === Person); // false  

    覆盖Person.prototype时,等价于进行如下代码操作:

      Person.prototype = new Object({
            getName: function() {
                return this.name;
            }
        });  

    而constructor始终指向创建自身的构造函数,所以此时Person.prototype.constructor === Object,即是:

     function Person(name) {
            this.name = name;
        };
        Person.prototype = {
            getName: function() {
                return this.name;
            }
        };
        var p = new Person("ZhangSan");
        console.log(p.constructor === Object);  // true
        console.log(Person.prototype.constructor === Object); // true
        console.log(p.constructor.prototype.constructor === Object); // true  

    怎么修正这种问题呢?方法也很简单,重新覆盖Person.prototype.constructor即可:

     function Person(name) {
            this.name = name;
        };
        Person.prototype = new Object({
            getName: function() {
                return this.name;
            }
        });
        Person.prototype.constructor = Person;
        var p = new Person("ZhangSan");
        console.log(p.constructor === Person);  // true
        console.log(Person.prototype.constructor === Person); // true
        console.log(p.constructor.prototype.constructor === Person); // true

    对象的_proto_隐式原型

    上面我们创建了两个对象,person1和person2,这两个对象,也都指向了Person构造函数的原型,这是因为每个对象都有一个隐藏的属性——“_proto_”,这个属性引用了创建这个对象的函数的prototype。即:person1._proto_ === Person.prototype
    这个_proto_是一个隐藏的属性,javascript不希望开发者用到这个属性值,有的低版本浏览器甚至不支持这个属性值。看下面的代码:

    console.log(Object.prototype);
    var obj = new Object();
    console.log(obj.__proto__);

    会发现打印了相同的内容: 

    obj这个对象本质上是被Object函数创建的,因此obj._proto_=== Object.prototype。我们可以用一个图来表示。 

    关于隐式原型,主要涉及到原型继承的主要原理

    通过原型创建对象的几种方式

    基本原型

    function Person(){ }  
    Person.prototype.name = "Nicholas"; 
    Person.prototype.age = 29; 
    Person.prototype.job = "Software Engineer"; 
    Person.prototype.sayName = function(){     
        alert(this.name); 
    };  

    当然这种方式只是说明原型的道理,实际使用中很少把属性写在原型中

    更简单的方式

    function Person(){ } 
    
    Person.prototype = {     
        name : "Nicholas",     
        age : 29,     
        job: "Software Engineer",     
        sayName : function () {         
            alert(this.name);     
        } 
    }; 

    这种方式只是上面方式的简单写法,通过对象字面量直接写完所有属性。效果和上面的写法是一样的,只是写法不一样。

    但是直接全部把属性和方法全部写在原型中,这并不现实,看下面的列子:

    function Person(){ }
    
    Person.prototype = {     
        constructor: Person,     
        name : "Nicholas",     
        age : 29,     
        job : "Software Engineer",     
        friends : ["Shelby", "Court"],     
        sayName : function () {         
            alert(this.name);     
        } 
    }; 
    
    var person1 = new Person(); 
    var person2 = new Person();  
    person1.friends.push("Van");  
    alert(person1.friends);    //"Shelby,Court,Van" 
    alert(person2.friends);    //"Shelby,Court,Van" 
    alert(person1.friends === person2.friends);  //true  

    上面的列子很容易看出,将属性写在原型中的问题,列子中的friends是个数组,引用数据类型在person1中修改了friends,添加了一个条数据之后,可以看到person1和person2对象的friends都发生了改变,因为prototype对象本身就是共享的,数组又是属于引用类型,改变了一个,其他的都会发生改变。

    所以,在实际中使用的更多的方法是构造函数与原型结合的方式

    构造函数与原型结合的方式

    function Person(name, age, job){     
        this.name = name;     
        this.age = age;     
        this.job = job;     
        this.friends = ["Shelby", "Court"]; 
    }  
    Person.prototype = {     
        constructor : Person,     
        sayName : function(){         
            alert(this.name);     
        } 
    } 
    
    var person1 = new Person("Nicholas", 29, "Software Engineer"); 
    var person2 = new Person("Greg", 27, "Doctor");  
    person1.friends.push("Van"); 
    alert(person1.friends);    //"Shelby,Count,Van" 
    alert(person2.friends);    //"Shelby,Count" 
    alert(person1.friends === person2.friends);    //false 
    alert(person1.sayName === person2.sayName);    //true   

    这里就可以看到,friends的属性在两个对象中就算改变了其中一个,并不会对另外一个产生影响。这种构造函数加原型的混成模式,是目前使用率,认可率最高的一种自定义类型的方式,所以,一般情况下,我们定义自定义类型默认都使用这种模式

    动态原型模式

    这种模式只是上面模式的变种,对于一些习惯书写面向对象语言的程序员来说,一个类要分开两个部分来写,是非常不习惯的,所以,就有了动态原型模式,其实无非就是,把之前分开两部分写的内容,全部提到函数中,加上判断就行了

    function Person(name, age, job){  
    
        //属性  
        this.name = name;     
        this.age = age;     
        this.job = job; 
    
        //方法  
        if (typeof this.sayName != "function"){              
            Person.prototype.sayName = function(){             
                alert(this.name);         
            };              
        } 
    }  
    
    var friend = new Person("Nicholas", 29, "Software Engineer"); 
    friend.sayName();  

    注意上面的判断,这种方式只有在sayName函数不存在的情况下,才会将它添加到原型中,如果sayName函数已经存在,那么这段代码就不会再运行,而且就算有很多方法的话,if语句也不用全部判断,只是需要判断一个就行了。


    这样的写法,对于java或者C#程序员相对来说感官上比较容易接受,而且写法也没有任何缺陷。但是,有一点不算是缺陷的缺点,javascript是一门动态语言,也就是说,属性和方法是随时可以添加的,如果全部写在构造函数里面去,反而看起来不是那么的灵活。所以,一般情况下,使用构造函数与原型的混合模式的还是比较多的

    可以用下面图来对原型进行理解:

  • 相关阅读:
    边界值分析
    等价类划分
    手工检测SQL注入(安全性测试)
    Web安全性测试
    Jmeter使用流程及简单分析监控
    使用可视化工具redisclient连接redis
    Java ThreadLocal的使用
    jvm中的新生代Eden和survivor区
    策略模式和工厂模式的区别
    java将一数组乱序排列
  • 原文地址:https://www.cnblogs.com/5huihui/p/4106578.html
Copyright © 2020-2023  润新知