美文网首页
JavaScript面向对象(三)

JavaScript面向对象(三)

作者: Vincent_Jiang | 来源:发表于2017-03-31 18:36 被阅读10次

    prototype 属性

    在 JavaScript 中,每个对象的构造函数都有一个 prototype 属性。该属性指向另一个对象,这个对象的所有属性和方法都会被其构造函数构造出来的实例继承。

    
    // 定义一个学生对象,拥有 name、sex 两个属性
    function Student(name, sex){
      this.name = name;
      this.sex = sex;
    }
    
    //创建两个实例
    var lucy = new Student("Lucy", "M");
    var jack = new Student("Jack", "F");
    
    console.log(Student.prototype); // Object {constructor: function}
    console.log(lucy.class); // undefined
    console.log(jack.class); // undefined
    
    // 通过 prototype 属性定义学生的班级,让其他实例对象都具备 class 属性
    Student.prototype.class = "ST1409";
    
    console.log(Student.prototype); // Object {class: "ST1409", constructor: function}
    console.log(lucy.class); // "ST1409"
    console.log(jack.class); // "ST1409"
    
    // 这时即使在设置 prototype 属性之前就实例化的对象,也都具备了 class 属性
    // 并且所有实例的 class 属性其实都是同一块内存地址,其引用便是 prototype 对象
    
    console.log(lucy.class == jack.class); // true
    console.log(lucy.class === jack.class); // true
    
    • isPrototypeOf() 用来判断 proptotype 对象和某个实例之间的关系
      console.log(Student.prototype.isPrototypeOf(lucy)); // true
      console.log(Student.prototype.isPrototypeOf(jack)); // true

    • hasOwnProperty() 用来判断某个属性,是自己本身定义的属性,还是来自于 prototype 的属性
      lucy.hasOwnProperty("name"); // true
      lucy.hasOwnProperty("class"); // flase

    constructor 属性

    每一个 prototype 和每一个 实例 对象里面,都会有一个 constructor 属性。这个属性默认指向的是自己的构造函数。当然,这个 constructor 属性是可以被修改的

    /**
     * 我们还是来定义一个学生的对象,创建两个该对象的实例。
     */
    function Student(name, sex) {
      this.name = name;
      this.sex = sex;
    }
    
    var lucy = new Student("Lucy", "M");
    var jack = new Student("Jack", "F");
    
    /**
     * 其实打印的就是该 Student 对象的构造函数声明
     * 下面的打印将会输出:
     * function Student(name, sex) {
     *   this.name = name;
     *   this.sex = sex;
     * }
     */
    
    console.log(lucy.constructor);
    console.log(Student.prototype.constructor);
    
    /**
     * 当然,它是可以被改变的。
     * 定义一个 Class 对象,然后将该对象赋值给 constructor 。
     */
    function Class(name) {
     this.name = name;
    }
    
    /**
     * 改变 constructor 属性的值。
     * 当然,直接通过实例对象也是可以改变的。
     * 如:lucy.constructor = Class;
     */
    Student.prototype.constructor = Class;
    
    /**
     * 下面的打印将会输出:
     * function Class(name) {
     *   this.name = name;
     * }
     */
    
    console.log(lucy.constructor);
    console.log(Student.prototype.constructor);
    
    

    相关文章

      网友评论

          本文标题:JavaScript面向对象(三)

          本文链接:https://www.haomeiwen.com/subject/udivottx.html