prototype详解

prototype详解_第1张图片
参考链接:
https://segmentfault.com/a/1190000003017751

   function Person(name){
       this.name=name;
   }
   Person.prototype.sayName=function(){
       console.log(this.name);
   }
   
   var person=new Person("xl");
   
   console.log(person.constructor); //输出 function Person(){}
   console.log(Person.prototype.constructor);//输出 function Person(){}
   console.log(Person.constructor); //输出 function Function(){}
 Person.prototype={
  sayName:function(){
         console.log(this.name);
     }
 }
 
 console.log(person.constructor==Person); //输出 false (这里为什么会输出false后面会讲)
 console.log(Person.constructor==Person); //输出 false
 
 console.log(Person.prototype.constructor);// 输出 function Object(){}  
 //这里为什么会输出function Object(){}
 //还记得之前说过constructor属性始终指向创建这个对象的构造函数吗?
 
 Person.prototype={
     sayName:function(){
         console.log(this.name);
     }
 }
 //这里实际上是对原型对象的重写:
 Person.prototype=new Object(){
     sayName:function(){
         console.log(this.name);
     }
 }
 //看到了吧。现在Person.prototype.constructor属性实际上是指向Object的。
 
 //那么我如何能将constructor属性再次指向Person呢?
 Person.prototype.constructor=Person;
    function Person(name){
        this.name = name;
    }
    
    var personOne=new Person("xl");
    
    Person.prototype = {
        sayName: function(){
            console.log(this.name);
        }
    };
    
    var personTwo = new Person('XL');
    
    console.log(personOne.constructor == Person); //输出true
    console.log(personTwo.constructor == Person); //输出false   
    //大家可能会对这个地方产生疑惑?为何会第二个会输出false,personTwo不也是由Person创建的吗?这个地方应该要输出true啊?
    //这里就涉及到了JS里面的原型继承
    //这个地方是因为person实例继承了Person.prototype原型对象的所有的方法和属性,包括constructor属性。当Person.prototype的constructor发生变化的时候,相应的person实例上的constructor属性也会发生变化。所以第二个会输出false;
    //当然第一个是输出true,因为改变构造函数的prototype属性是在personOne被创建出来之后。

js对象的一般生成方法

//我们希望每个stu拥有属于自己的name和age属性
function Student(name, age) {
  this.name = name;
  this.age = age;
}

//所有的stu应该共享一个alertName()方法
Student.prototype = {
  constructor : Student,
  alertName : function() {
                alert(this.name);
              }
}

var stu1 = new Student("Jim", 20);
var stu2 = new Student("Tom", 21);

stu1.alertName();  //Jim  实例属性
stu2.alertName();  //Tom  实例属性

alert(stu1.alertName == stu2.alertName);  //true  共享函数

你可能感兴趣的:(技术杂项)