When I tried with a single class and property it works fine. But if I'm using it with multiple class properties, it throws an error, such that mixchi
is not a function.
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
I don't know where you took that, but Backbone's extend
function doesn't work like that.
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.
Your first example works because you're defining himavari
in the classProperties
object (second param of extend
) which is the equivalent of a static function.
// 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>