了不起的node.js(二)

JavaScript中没有class关键词,类只能通过函数定义:

function Animal() {}

要给所有Animal的实例定义函数, 可以通过prototype属性来完成:

Animal.prototye.eat = function(food){
  //eat method
}

这里值得一提的是,在prototype的函数内部,this并非像普通函数那样指向global对象,而是指向通过该类创建的实例对象:

function Animal (name) {
  this.name = name
}
Animal.prototype.getName() = function {return this.name}
var a= new Animal('tobi')
a.getName()

继承

JavaScript有基于原型的继承的特点。通常,你可以通过以下方式来模拟类继承。
定义一个要继承自Animal的构造器:

function Ferret(){}
Ferret.prototype = new Animal()
Ferret.prototype.type = 'domestic'
// 通过prototype和call来调用父类函数
Ferret.prototype.eat = function(food){
  Animal.prototype.eat.call(this, food)
  // Ferret的特性
}

这项技术很赞。它是同类中最好的(相比其他函数式技巧),而且它不会破坏instanceof操作结果:

var animal = new Animal()
animal instanceof Animal // true
animal instanceof Ferret // false
var ferret = new Ferret()
ferret instanceof Animal //true
ferret instanceof Ferret // true

它的最大不足就是声明继承的时候创建的对象总是进行初始化(Ferret.prototype=new Animal),这种方式不太友好。一种解决该问题的方法就是在构造器中添加判断条件:

function Animal(a){
  if(false !== a) return
  // 初始化
}
Ferret.prototype = new Animal(fales)

另外一个办法就是再定义一个新的空构造器,并重写它的原型

function Animal(){
}
function f(){}
f.prototype = Animal.prototype;
Ferret.prototype = new f

V8给我们提供了更简洁的解决方案

var util = require('util')
util.inherits(Ferret, Animal)

try catch{}

try/catch 允许进行异常捕获。下述代码会抛出异常:

var a = 5
a()
TypeError: a is not a function

当函数抛出错误时,代码就停止执行了:

function (){
  throw new Error('hi')
  console.log('hi')  //这里不会执行
}

若使用try/catch则可以进行错误处理,并让代码继续执行下去

function(){
  var a = 5
  try{
  a()
  }catch(e){
  e instanceof Error //true
}
console.log('you got here')  //通过try/catch  以后就可以执行到了

https://www.processon.com/i/568c6ea4e4b0e51d149a085f
这个网站解决了大家开始设计阶段的问题,轻量级的各种设计模型,强烈推荐。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值