【问题标题】:JavaScript instanceof errorJavaScript 实例错误
【发布时间】:2014-08-19 08:17:39
【问题描述】:

我试图将错误作为对象抛出,以便我可以创建一个 if 语句来检查错误是否是紧急错误。为此,我需要检查error instanceof myEmergencyFunc。但如果我有一个子功能,这会失败。以这个小提琴为例:http://jsfiddle.net/tvs4qjgs/

var someName = function(){
    this.LogEmergency = function(message){
        this.message = message;
        return this;
    };
    return this;
};

var a = someName().LogEmergency('my error');

console.log(a instanceof someName().LogEmergency);

我做错了什么?

【问题讨论】:

  • 阅读更多关于JS中的构造函数和“new”的使用。
  • 在构造函数中创建方法被认为是不好的做法。尽可能避免这种类型的构造函数:这就是原型的用途!还要考虑以下编码标准/约定:构造函数以大写字母开头,属性和方法不是(所有名称都是 camleCased)

标签: javascript instanceof throw


【解决方案1】:

问题

var a = someName().LogEmergency('my error');

a 指的是全局对象,而不是您认为已创建的对象(如果您在浏览器中运行此代码,则为 window

console.log(a === window) --> 将是真的。

您的最终结果是错误的,因为您正在与错误的对象进行比较。如果您想知道原因,那是因为您在创建对象时缺少关键字 new。 使用 new 调用函数会触发构造函数机制,该机制会创建一个新对象并返回它。

在没有 new 的情况下调用函数并在函数内返回“this”会返回全局对象。

您必须对代码进行以下更改

var someName = function(){
  this.LogEmergency = function(message){
    this.message = message;
    return this;  // here this refers to the new object you created
  };
  return this; // here also this refers to the new object you created
               // here the return is redundant as this is implicit.
};

// new operator is the keyword for creating objects.
// the meaning of "this" inside the function completely changes without the operator
var a = new someName().LogEmergency('my error'); 

在上面的代码中a 现在指的是您创建的新实例。 最后检查创建的对象是否是someone的实例

console.log(a instanceof someName); //will be true

阅读更多关于构造函数here

【讨论】:

  • new someName() 周围不需要括号?
  • 如果您不传递任何参数,() 是可选的。新的 someName 也可以使用
  • 不,你误解了我的意思。我在问您是否需要编写(new someName()).LogEmergency('my error') 以确保在您的新对象上调用LogEmergency,而不是在调用someName() 的结果上调用,然后将其本身传递给new。跨度>
  • @LightnessRacesinOrbit:确实不是,但我也强烈建议使用它们:LogEmergency,对我来说,看起来像一个构造函数。方法本身使用this,所以var a = new someName(); var b = new a.LogEmergency('foobar');玩起来很危险
  • @BOSS:new someName().LogEmergency() 中的调用方括号不是可选的。 var a = new someName.LogEmergency(); 会抛出一个 TypeError。使用 var a = (new someName).LogEmergency() 或您拥有的代码,我更喜欢建议的轨道中的 Lightness Races 版本,thgouh
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2014-09-30
  • 2013-07-28
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-12-08
  • 2017-04-18
相关资源
最近更新 更多