zoukankan      html  css  js  c++  java
  • 理解constructor属性

    constructor属性始终指向创建当前对象的构造函数

    一般情况下的constructor的属性非常容易理解。

    var arr=[1,2,3,4,5];//等价于var arr=new Array(1,2,3,4,5);
    alert(arr.constructor===Array)//true
    var Foo=function(){}//等价于var Foo=new Function(){};
    alert(Foo.constructor===Function);//true
    //
    由构造函数实例化一个obj对象
    var obj=new Foo();
    alert(obj.constructor===Foo);true

    alert(obj.constructor.constructor===Function);true

    但constructor遇到prototype时,有几点需要理清。

    1.每个函数(F)都有一个默认的属性prototype,而这个prototype的constructor默认指向这个函数(F)。

    function Person(name){
    this.name=name;
    }
    Person.prototype.getName=function(){return this.name;}
    var me=new Person('asan');
    alert(me.constructor===Person);//true
    alert(Person.prototype.constructor===Person)//true

    2.当我们重定义构造函数的prototype属性时,注意constructor属性此时的指向

    function Person(name){
    this.name=name;
    }
    Person.prototype={
    getName:function(){
    return this.name;
    }
    }
    var me=new Person('asan');
    alert(me.constructor===Person);//false
    alert(Person.prototype.constructor===Person)//false

    为什么呢,原因是重定义Person.prototype时,等价于如下代码

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

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

    Person.prototype.constructor===Object;//true

    怎么修正这个问题呢,很简单,重新把Person.prototype.constructor指向构造函数本身即可。

    function Person(name){
    this.name=name;
    }
    Person.prototype={
    getName:function(){
    return this.name;
    }
    }
    Person.prototype.constructor=Person;
    var me=new Person('asan');
    alert(me.constructor===Person);//true
    alert(Person.prototype.constructor===Person)//true







  • 相关阅读:
    Qt多表格滚动条同步
    Trie树
    计算机网络笔记--网络层--ICMP协议
    计算机网络笔记--网络层--NAT
    计算机网络笔记--IP地址
    计算机网络笔记--网络层--ARP协议
    计算机网络笔记--网络层1IP协议
    const与指针
    c/c++笔记--指向数组的指针与二维数组
    机试笔记9--二叉树的遍历
  • 原文地址:https://www.cnblogs.com/cwWeb/p/2377254.html
Copyright © 2011-2022 走看看