深入淺析JavaScript中的constructor

字號:


    constructor 屬性返回對創(chuàng)建此對象的數(shù)組函數(shù)的引用。本文給大家介紹JavaScript中的constructor ,需要的朋友參考下吧
    定義和用法
    constructor 屬性返回對創(chuàng)建此對象的數(shù)組函數(shù)的引用。
    語法
    object.constructor
    constructor,構(gòu)造函數(shù),對這個名字,我們都不陌生,constructor始終指向創(chuàng)建當前對象的構(gòu)造函數(shù)。
    這里有一點需要注意的是,每個函數(shù)都有一個prototype屬性,這個prototype的constructor指向這個函數(shù),這個時候我們修改這個函數(shù)的prototype時,就發(fā)生了意外。如
    function Person(name,age){
    this.name = name;
    this.age = age;
    }
    Person.prototype.getAge = function(){
    return this.age;
    }
    Person.prototype.getName = function(){
    return this.name;
    }
    var p = new Person("Nicholas",18);
    console.log(p.constructor); //Person(name, age)
    console.log(p.getAge()); //18
    console.log(p.getName()); //Nicholas
    但是如果是這樣:
    function Person(name,age){
    this.name = name;
    this.age = age;
    }
    Person.prototype = {
    getName:function(){
    return this.name;
    },
    getAge:function(){
    return this.age;
    }
    }
    var p = new Person("Nicholas",18);
    console.log(p.constructor); //Object()
    console.log(p.getAge()); //18
    console.log(p.getName()); //Nicholas
    結(jié)果constructor變了。
    原因就是prototype本身也是對象,上面的代碼等價于
    Person.prototype = new Object({
    getName:function(){
    return this.name;
    },
    getAge:function(){
    return this.age;
    }
    });
    因為constructor始終指向創(chuàng)建當前對象的構(gòu)造函數(shù),那么就不難理解上面代碼p.constructor輸出的是Object了。
    對于修改了prototype之后的constructor還想讓它指向Person怎么辦呢?簡單,直接給Person.prototype.constructor賦值就可以了:
    Person.prototype = {
    constructor:Person,
    getName:function(){
    return this.name;
    },
    getAge:function(){
    return this.age;
    }
    }
    以上所述是小編給大家介紹的JavaScript中的constructor ,希望對大家有所幫助!