美文网首页
《了不起的Node.js》摘要 JavaScripts概览(二)

《了不起的Node.js》摘要 JavaScripts概览(二)

作者: 玖伍2七 | 来源:发表于2019-05-08 15:59 被阅读0次

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  以后就可以执行到了

相关文章

网友评论

      本文标题:《了不起的Node.js》摘要 JavaScripts概览(二)

      本文链接:https://www.haomeiwen.com/subject/bxzmoqtx.html