骨干js不止一个类,功能不起作用

问题描述 投票:0回答:1

当我尝试使用单个类和属性时,它可以正常工作。但是,如果我使用多个类属性,它会抛出一个错误,这样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
javascript backbone.js backbone-model
1个回答
0
投票

我不知道你把它拿在哪里,但是Backbone's extend功能并不像那样。

How to use extend

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

要创建自己的Model类,可以扩展Backbone.Model并提供实例属性,以及可直接附加到构造函数的可选classProperties。

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

// 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>

推荐问答