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







  • 相关阅读:
    codeforces 1C(几何题)
    poj 1015 Jury Compromise
    poj 1466 计算直线的交点数
    poj 1228 凸包第一题
    2012 MUTC 3 总结
    用优先队列优化Dij的一个代码
    有关排序时,上移,下移的处理思路
    有关缓存的思考
    python备份文件2 分类: python 20130315 15:16 233人阅读 评论(0) 收藏
    lambda表达式使用方法详解 分类: python 20130315 10:58 396人阅读 评论(0) 收藏
  • 原文地址:https://www.cnblogs.com/cwWeb/p/2377254.html
Copyright © 2011-2022 走看看