Reputation: 15006
I'm trying to learn object-oriented javascript. Working with a simple method I want to do this:
var users = function(url){
this.url = url;
this.log = function(){
console.log(this.url);
}
}
var apiPoint = "https://www.zenconomy.se/api/admin/tracking?format=json"
var liveUsers = new users(apiPoint)
liveUsers.log()
However, I've learned that it's often a good idea to pass variables into functions when working with normal functions, in objects however, this seems a bit clunky.
var users = function(url){
this.url = url;
this.log = function(url){
console.log(url);
}
}
var apiPoint = "here is my url"
var liveUsers = new users(apiPoint)
liveUsers.log(liveUsers.url)
Both methods work. What are the pros and cons of the different approaches, assuming that users.log only ever need properties from inside the users-class.
Upvotes: 8
Views: 128
Reputation: 349
you just mentioned you are trying to learn OOP in javascript, but actually, consider the log function in your user
object, if there is no users instance, no log
method eigther. That's not the same concept according to OO in C++ or C#. In my opinion, prototype
will best describe the oop, do as following:
var users = function(url){
this.url = url;
}
users.prototype.log = function(){
console.log(this.url);
}
in this way, log
will not be in any instance of users
, it exists in __proto__
which is a reference of prototype
in any instance. That means when you create instances, they share all the functions, same as C++ or C#. finally, you should never use the second sample in your post, that's not OO things.
Upvotes: 1
Reputation:
If you want log
to always print the object's URL, then of course you would not pass in the object's URL as a parameter, since log
can get it itself.
If you want to log various properties of the object, I'd suggest making separate routines such as logUrl
and logBlah
for the individual cases.
If you want log
to print some arbitrary value, then it goes without saying that you need to pass in the value.
If there is nothing about logging that relates to the object, then you can just have a logging routine independent of the object that logs whatever you pass it.
Upvotes: 0