So I have a function which looks like this:
function Students(){
// Function add:
// Returns: add page
this.add = function(){
// Get template
$.get('view/students/new.html', function(template){
// Templating
var html = Mustache.to_html(template);
// When document ready, write template to page
$('document').ready(function(){
$('#container').html(html);
});
});
};
};
When I try to call it's add
function like so:Students.add();
I get the error:
Uncaught TypeError: Object function Students(){...}has no method 'add'
What gives?
To use that implementation of Students
, you should do this:
var students = new Students();
students.add();
However, that's probably not what you want. You probably meant to define Students
like this:
var Students = {
add: function() {
$.get( /* ... */ );
}
};
Then you can call it like this:
Students.add();
Students is intended to be called as a constructor.
var s = new Students();
s.add()
Inside of Students
, this
will be a new object that inherits from Students's prorotype, and is returned automatically. So saying
this.add = function() ....
is adding the add
function onto this object that's being returned. But the function will be created de novo each and every time you invoke this function. Why not add it to the prototype instead, so the function will exist only once, and not have to be needlessly re-created each and every time.
Students.prototype.add = function(){
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With