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







  • 相关阅读:
    C 找到该列最大的前两个数字
    C 寻找和最大的子序列
    C 找出最长的回文子串(不区分大小写)
    C 字符串数组
    C 寻找重复字符并输出他们的位置
    C 寻找0~100的守形数
    C 在外部函数中修改指针变量
    C int转为二进制 再进行与操作
    C 计算阶乘之和
    C 奇偶校验
  • 原文地址:https://www.cnblogs.com/cwWeb/p/2377254.html
Copyright © 2011-2022 走看看