已存在实例的属性取决于我如何影响原型属性

时间:2016-03-31 14:56:14

标签: javascript prototype

有人可以解释一下为什么如果我将对象影响到原型,属性不会添加到此对象的现有实例中,而如果我单独影响原型的每个属性,则属性将添加到所有已定义的实例中。下面的示例1和示例2说明了我的问题(https://jsfiddle.net/tgyakpe0/5/)。示例的结果是:

  • 示例1 我父亲是英国人 我是英国人

  • 示例2 我父亲是英国人 我未定义

  • 示例3 我父亲是英国人和律师 我是英国人和律师

  • 示例4转变 我父亲是英国人和律师 我是英国人和律师

在示例4中,我为这种行为做了一个简单的转变,但我想知道它是否是一种安全的做法。 谢谢。

/* example 1 */
        function person1(first, last, age, eyecolor) {
            this.firstName = first;
            this.lastName = last;
            this.age = age;
            this.eyeColor = eyecolor;
        }
        var me1=new person1("lolo","lala",35,"blue");
        person1.prototype.nationality="English";
        var myFather1 = new person1("John", "Doe", 50, "blue");
        document.getElementById("example1").innerHTML ="* example 1 <br>My father is " + myFather1.nationality+" <br>I am "+me1.nationality;
        /* example 2 */
        function person2(first, last, age, eyecolor) {
            this.firstName = first;
            this.lastName = last;
            this.age = age;
            this.eyeColor = eyecolor;
        }
        var me2=new person2("lolo","lala",35,"blue");
        person2.prototype={nationality:"English"};
        var myFather2 = new person2("John", "Doe", 50, "blue");
        document.getElementById("example2").innerHTML ="* example 2 <br>My father is " + myFather2.nationality+" <br>I am "+me2.nationality;
        /* example 3 */
        function person3(first, last, age, eyecolor) {
            this.firstName = first;
            this.lastName = last;
            this.age = age;
            this.eyeColor = eyecolor;
        }
        var me3=new person3("lolo","lala",35,"blue");
        person3.prototype.job="lawyer";
        person3.prototype.nationality="English";

        var myFather3 = new person3("John", "Doe", 50, "blue");
        document.getElementById("example3").innerHTML ="* example 3 <br>My father is " +myFather3.nationality+" and "+myFather3.job+" <br>I am "+me3.nationality+" and "+me3.job;
        /* example 4 */
        function proto(f,prot){
          for (k in prot) {
          f.prototype[k]=prot[k];
          }
        }
        function person4(first, last, age, eyecolor) {
            this.firstName = first;
            this.lastName = last;
            this.age = age;
            this.eyeColor = eyecolor;
        }
        var me4=new person4("lolo","lala",35,"blue");
        prototo={job:"lawyer",nationality:"English"};
        proto(person4,prototo);
        var myFather4 = new person4("John", "Doe", 50, "blue");
        document.getElementById("example4").innerHTML ="* example 4 <br>My father is " +myFather4.nationality+" and "+myFather4.job+" <br>I am "+me4.nationality+" and "+me4.job;

0 个答案:

没有答案