zoukankan      html  css  js  c++  java
  • 对象,函数,构造函数this,原型

    var Cat = {                    

      name :'',                   

      color :''                    

    }

    var cat1 = {

      cat1.name  = "大毛";

          cat1.color = "黄色";

    }

    Cat作为一个对象,有名字和颜色两个属性

    function Cat(name,color){                                             

      return{                                                                 

        name:name,                                                    

        color:color                                                       

      }

    }

    Cat作为一个函数

    var cat1 = Cat("大毛","黄色");

    var cat2 = Cat("二毛","黑色");

    生成实例对象,即调用函数

    function Cat(name,color){

      this.name = name;

          this.color = color;

    }

    构造函数,是一个普通函数,但是内部使用了this变量,对构造函数使用new运算符,就能生成实例,并且this变量会绑定在实例对象上。

    var cat1 = new Cat("大毛","黄色");

    var cat2 = new Cat("二毛",“黑色”);

    alert(cat1.constructor == Cat);//true

    alert(cat2.constructor == Cat);//true

    alert(cat1.instanceof Cat);

    alert(cat2.instanceof Cat);

    function Cat(name,color){

      this.name =name;

      this.color = color;

      this.type = "猫科动物";                              //对于都有的属性每次生成一个实例,会多占用内存

      this.eat = function(){alert("吃老鼠");};

    }

         this将绑定在实例对象上

    function Cat(name,color){

      this.name = name;

      this.color = color;

    }

    Cat.prototype.type = "猫科动物"; 

    Cat.prototype.eat = function(){

        alert("吃老鼠");       

      };

    alert(Cat.prototype.isPrototypeOf(cat1));

    alert(Cat.prototype.isPrototypeOf(cat2));

    综上所述,对于实例对象,自有属性可以使用传值调用,统一变量也可放在构造函数中,对于都一样的属性和方法,则使用的是prototype

    http://www.ruanyifeng.com/blog/2010/05/object-oriented_javascript_encapsulation.html

  • 相关阅读:
    HTML知识点链接
    Apache和PHP的安装
    MySql的安装
    MY_FIRSH_MODULE
    【PAT甲级】1053 Path of Equal Weight (30 分)(DFS)
    Atcoder Grand Contest 039B(思维,BFS)
    Codeforces Round #589 (Div. 2)E(组合数,容斥原理,更高复杂度做法为DP)
    Codeforces Round #589 (Div. 2)D(思维,构造)
    【PAT甲级】1052 Linked List Sorting (25 分)
    【PAT甲级】1051 Pop Sequence (25 分)(栈的模拟)
  • 原文地址:https://www.cnblogs.com/100bluesea/p/3490359.html
Copyright © 2011-2022 走看看