zoukankan      html  css  js  c++  java
  • JS创建对象

    本人常用的创建对象的方式,仅供参考,欢迎吐槽,谢谢!

    创建对象
    1、对象字面量,即使用大括号,如下:

    (function(){
    
      var obj = {
        id: 1,
        desc: '创建对象测试开始啦!',
        show: function(){
          console.log("id=%d, desc=%s", this.id, this.desc);
        }
      };
     
      obj.show();
    })();


    2、构造函数

    (function(){
    
      function Animal(name, age){
        this.name = name;
        this.age = age;
        this.show = function(){
          console.log("该动物是%s,今年%d岁", this.name, this.age);
        }
      }
      
      var cat = new Animal('猫咪', 3);
      cat.show();
    
    })();

    一种错误:

    (function(){
    
      function Animal(){
      }
      
      Animal.prototype.name = '猫咪';
      Animal.prototype.age = 3;
      Animal.prototype.show = function(){
         console.log("该动物是%s,今年%d岁", this.name, this.age);
      };
     
      animal = Animal();
      animal.show();//TypeError: animal is undefined
    
    })();

    解决方案

    (function(){
    
      function Animal(){
        if( !(this instanceof Animal) ){
          return new Animal(); 
        }
      }
      
      Animal.prototype.name = '猫咪';
      Animal.prototype.age = 3;
      Animal.prototype.show = function(){
         console.log("该动物是%s,今年%d岁", this.name, this.age);
      };
     
      animal = Animal();
      animal.show();//该动物是猫咪,今年3岁
    
    })();


    3、原型模式

    (function(){
    
      function Animal(){
    
      }
      
      Animal.prototype.name = '猫咪';
      Animal.prototype.age = 3;
      Animal.prototype.show = function(){
         console.log("该动物是%s,今年%d岁", this.name, this.age);
      };
      
      var animal = new Animal();
      animal.show();//该动物是猫咪,今年3岁
      
      animal.name = "狗熊";
      animal.age = 14;
      animal.show();//该动物是狗熊,今年14岁
      
      delete animal.name;
      animal.show();//该动物是猫咪,今年14岁
    
    })();

    备注:当删除对象的属性时,为啥从该对象的name,从狗熊变成了猫咪了呢?这是跟JS中属性的查找有关!首先其先从该对象的属性中查找若有,则立即返回,当没有,再到其原型中查找,若有则立即返回,最后当找不到时,则返回undefined

    什么是原型?

    1、我们创建的每一个函数都有一个prototype属性,这个属性是一个对象,它的用途是包含有特定类型的所有实例共享的属性和方法。
    2、只要创建了一个新函数,就会为该函数创建一个prototype属性。默认情况下,所有prototype属性都会自动获得一个constructor属性,这个属性包含一个指向prototype属性所在函数的指针。这样,函数以及函数原型之间就形成了循环指向了。
    3、每当调用构造函数创建一个新实例后,该实例的内部将包含一个指针(一般指__proto__),指向构造函数的原型属性。

    参考资料:

    有图的,很有意思:http://www.cnblogs.com/maxupeng/archive/2010/12/28/1918480.html

  • 相关阅读:
    JS基础学习四:绑定事件
    常用JS事件对象
    jq 使用手册
    access数据库根据指定日期进行查询
    IP地址变动后,https://localhost:1158/em无法访问解决办法
    结构体对齐方式
    宏得到当前函数的名字
    std::list保存大量数据时,类型即是无析构函数,该list析构时会占用大量CPU
    装了vs2010 SP1后,开机速度慢
    查询SQL Server版本号
  • 原文地址:https://www.cnblogs.com/xiaoxian1369/p/4908793.html
Copyright © 2011-2022 走看看