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







  • 相关阅读:
    豆瓣书籍数据采集
    动画精灵与碰撞检测
    图形
    模块
    对象
    函数
    列表与字典
    python 感悟
    SqlServer自动备份数据库(没有sql代理服务的情况下)
    关于AD获取成员隶属于哪些组InvokeGet("memberOf")的问题
  • 原文地址:https://www.cnblogs.com/cwWeb/p/2377254.html
Copyright © 2011-2022 走看看