对象,函数,构造函数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

 

 

 

posted @ 2013-12-25 11:58  100bluesea  阅读(234)  评论(0编辑  收藏  举报