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

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了骨干js不止一个类,功能不起作用相关的知识,希望对你有一定的参考价值。

当我尝试使用单个类和属性时,它可以正常工作。但是,如果我使用多个类属性,它会抛出一个错误,这样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功能并不像那样。

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>

以上是关于骨干js不止一个类,功能不起作用的主要内容,如果未能解决你的问题,请参考以下文章

java代码在片段活动中不起作用

Javascript代码片段在drupal中不起作用

Snackbar 在片段类中不起作用

骨干转JSON

另一个片段内的谷歌地图 - 像 onLocationChanged 这样的功能不起作用

在内部片段类中使用ListView