backbone js 不止一个 class 并且功能不工作

backbone js more than one class and function not working

当我尝试使用单个 class 和 属性 时,它工作正常。但是如果我将它与多个 class 属性一起使用,它会抛出一个错误,这样 mixchi 就不是一个函数。

var sinchan = Backbone.Model.extend({}, {
    himavari: function() {
        return "sinchan nuhara"; 
    }
}, {
    mixchi: function() {
        return "10";
    }
});
console.log(sinchan.himavari());//output sinchan nuhara
console.log(sinchan.mixchi());// output TypeError: sinchan.mixchi is not a function

我不知道你从哪里弄来的,但是 Backbone's extend 函数不是那样工作的。

如何使用extend

Backbone.Model.extend(properties, [classProperties])

To create a Model class of your own, you extend Backbone.Model and provide instance properties, as well as optional classProperties to be attached directly to the constructor function.

您的第一个示例有效,因为您在 classProperties 对象(extend 的第二个参数)中定义了 himavari,这相当于静态函数。

// this defines a custom model class
var MyModelClass = Backbone.Model.extend({
  instanceFunc: function() {
    return this.get('test');
  },
  otherInstanceFunc: function() {
    return this.get('other');
  }
}, {
  // 'this' is not available in the following functions
  staticFunc: function() {
    return "static";
  },
  otherStaticFunc: function() {
    return "other static"
  }
});

// This is how you create an instance of a custom model class
var modelInstance = new MyModelClass({
  test: 'test value',
  other: 'other'
});

console.log(modelInstance.instanceFunc());
console.log(modelInstance.otherInstanceFunc());
// console.log(modelInstance.staticFunc()); 
// => TypeError: modelInstance.staticFunc is not a function
// console.log(modelInstance.otherStaticFunc());
// => TypeError: modelInstance.otherStaticFunc is not a function

// console.log(MyModelClass.instanceFunc());
// => TypeError: MyModelClass.instanceFunc is not a function
// console.log(MyModelClass.otherInstanceFunc());
// => TypeError: MyModelClass.otherInstanceFunc is not a function
console.log(MyModelClass.staticFunc());
console.log(MyModelClass.otherStaticFunc());
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/underscore.js/1.8.3/underscore-min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/backbone.js/1.3.3/backbone-min.js"></script>