Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Constructor and prototypes in javascript

I'm reading a snippet of code that defines a constuctor

var Resource = function(data) {
    angular.extend(this, data);
}

and then subsequently defines a method to it.

Resource.query = function(url) {
    console.log(url);
}

Can I ask how this works? I know functions are objects as well, and is this the equivalent of the following? But if so, then what happens to the constructor function?

var data = {};
data.query = function(url) {
    console.log(url);
}

Also, why wouldn't we simply define it on the prototype instead?

Resource.prototype.query = function(url) {
    console.log(url);
}

http://jsfiddle.net/HPg6A/

like image 273
Dan Tang Avatar asked Jun 04 '26 15:06

Dan Tang


1 Answers

You would define methods on the prototype only if they are meant to be called on specific instances. When methods are defined directly as constructor members, it's usually to mimic static methods.

Basically, when a method relates very closely to a class, but doesn't make much sense as an instance method, it can be implemented as a static method.

I think that you will agree with me that the second example makes more sense and if you do, you already understood the difference.

1-

var user = new User();

user.findUser('somequery').then(...);

2-

User.findUser('somequery').then(...);
like image 125
plalx Avatar answered Jun 07 '26 09:06

plalx



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!