Javascript函数没有返回正确的值

时间:2017-03-21 15:36:34

标签: javascript

所以我有这段代码:

Rates Table      

create_table "rates", force: :cascade do |t|
    t.integer  "origin_id"
    t.integer  "destination_id"
    t.integer  "carrier_id"
    t.integer  "shipment_category_id"
    t.decimal  "cost",                 precision: 10, scale: 2
    t.integer  "unit_of_measure_id"
    t.datetime "created_at",                                    null: false
    t.datetime "updated_at",                                    null: false
    t.integer  "seller_id"
    t.index ["carrier_id"], name: "index_rates_on_carrier_id", using: :btree
    t.index ["destination_id"], name: "index_rates_on_destination_id", using: :btree
    t.index ["origin_id"], name: "index_rates_on_origin_id", using: :btree
    t.index ["seller_id"], name: "index_rates_on_seller_id", using: :btree
    t.index ["shipment_category_id"], name: "index_rates_on_shipment_category_id", using: :btree
    t.index ["unit_of_measure_id"], name: "index_rates_on_unit_of_measure_id", using: :btree

Rates Model
  belongs_to :origin, :class_name => 'Port'
  belongs_to :destination, :class_name => 'Port'
  belongs_to :seller, :class_name => 'Carrier'
  belongs_to :carrier
  belongs_to :shipment_category
  belongs_to :unit_of_measure

但是当警报被触发时,我得到一个未定义的错误而不是21,私有方法是否不能使用返回?谢谢!

3 个答案:

答案 0 :(得分:2)

使用function() {}语法定义函数时,总是明确需要返回值,即不仅来自nn,还来自所有中间函数



function Class1() {
  this.i = 1;
  var that = this;

  function nn() {
    return 21;
  }
  this.aa = function() {
    return nn();
  }
  this.bb = function() {
    return this.aa();
  }
  this.cc = function() {
    return this.bb();
  }
}
var o = new Class1();
var b = o.cc();
alert(b); // "21"




答案 1 :(得分:0)

除了上面的答案,'这个'上下文在你的函数中看起来很怪异。如果你不想将这个上下文绑定到每个函数,也许你对箭头函数更好。我还认为,在使用“课程”时,最好将私人和公共职能分开。像这样。

function Class1() {
  var _nn = function () {
    return 21;
  }
  var _aa = function () {
    return _nn();
  }
  var _bb = function () {
    return _aa();
  }
  var cc = function () {
    return _bb();
  };

  return {
    cc
  };
}
var o = new Class1();
var a = o.cc();
console.log(a);

更容易理解,只有cc才是公共功能。

答案 2 :(得分:0)

所以使用箭头函数它会看起来像这样,你可以在你的私有函数中使用Class1这个上下文而不用 var that = this;或使用bind。

function Class1() {
  this.privateThing = 'private';

  var _nn = ()  => { return this.privateThing; };
  var _aa = () => { return _nn(); };
  var _bb = () => { return _aa(); };
  var cc = () => { return _bb(); };

  return {
    cc
  };
}