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.
We can pass the data to the methods in form of arguments and an object is an instance of a class that is created dynamically. The basic data types can be passed as arguments to the C# methods in the same way the object can also be passed as an argument to a method.
To pass an object as an argument we write the object name as the argument while calling the function the same way we do it for other variables. Syntax: function_name(object_name); Example: In this Example there is a class which has an integer variable 'a' and a function 'add' which takes an object as argument.
When we pass a primitive type to a method, it is passed by value. But when we pass an object to a method, the situation changes dramatically, because objects are passed by what is effectively call-by-reference. Java does this interesting thing that's sort of a hybrid between pass-by-value and pass-by-reference.
Object.assign() The Object.assign() method copies all enumerable own properties from one or more source objects to a target object. It returns the modified target object.
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.
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