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;
    }
  };

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值