Javascript定义类的方法

1. 经典的方式

function Cat() {
    this.name = "大毛";
  }

生成实例的时候用new关键字:

var cat1 = new Cat();
  alert(cat1.name); // 大毛

使用prototype,在外部定义类的方法:

Cat.prototype.makeSound = function(){
    alert("喵喵喵");
  }

 用Propotype可以实现对象之间数据的分享。

二、object.create()

var cat1 = Object.create(Cat);
  alert(cat1.name); // 大毛
  cat1.makeSound(); // 喵喵喵

使用Object.create不使用new关键字。但其实没什么用处,浏览器支持方面,IE不支持Object.create。如果不支持的浏览器可以用下面的语法补充:

if (!Object.create) {
    Object.create = function (o) {
       function F() {}
      F.prototype = o;
      return new F();
    };
  }

极简主义法:

var Cat = {
    createNew: function(){
      // some code here
    }
  };

极简主义法的继承:

var Animal = {
    createNew: function(){
      var animal = {};
      animal.sleep = function(){ alert("睡懒觉"); };
      return animal;
    }
  };

 子类定义:

var Cat = {
    createNew: function(){
      var cat = Animal.createNew();
      cat.name = "大毛";
      cat.makeSound = function(){ alert("喵喵喵"); };
      return cat;
    }
  };

猜你喜欢

转载自tntxia.iteye.com/blog/2237770