Are we declaring a function as a method on a variable? - javascript

I have been learning JS on my own and completed an 8 hour course on the basics. Now I am following another course where the lecturer, as it seems to me, is creating a function using dot notation. I am not sure if this is what is happening and I am having a hard time understanding exactly what it is doing.
function Person(fName, lName) {
this.firstName = fName
this.lastName = lName
}
const person1 = new Person("Bruce", "Wayne")
const person2 = new Person("Bat", "Man")
person1.getFullName = function () {
return this.firstName + ' ' + this.lastName
}
console.log(person1.getFullName())
The part I am confused about is:
person1.getFullName = function () {
return this.firstName + ' ' + this.lastName
}
I see in the Person() function we are creating an object called person1 using "this" and a key to pass in parameters as values for those keys. However it looks to me like there is a function being assigned to the person1 object and what I am assuming is the name of the function, looks like a method on the person1 object using dot notation. Can anyone explain how this works?

The line
person1.getFullName = ...
is a normal assignment statement. It assigns the value on the right hand side to the property getFullName of the object in person1. If the property doesn't exist yet it will be created.
Functions are values (objects) like any other in JavaScript and thus they can be used everywhere were a value is expected.
So yes, person1.getFullName will contain a function and it can be called like any other function: person1.getFullName().

Objects have properties.
Properties have values.
Functions are a value.
If the value of a property is a function then we call that a method.
That's all there is to it.

function Person(fName, lName) {
this.firstName = fName
this.lastName = lName
}
const person1 = new Person("Bruce", "Wayne")
const person2 = new Person("Bat", "Man")
person1.getFullName = function () {
return this.firstName + ' ' + this.lastName
}
console.log(person1.getFullName())
Basically a new property called getFullName is created for the object person1. This new property is defined to return the first name and the lastname of the person1 object. So when you call console.log(person1.getFullName()) this will print the firstname and the lastname of the person1.

Related

Passing parameters as arguments in OOP

I have just started to learn OOP. I am still trying to understand how everything works. I am trying to make a new function that will basically allow me to create a new object by passing the parameters of said class.
Is this even possible, and if so what am I doing wrong?
As stated, still learning so any advice will be appreciated.
class Person {
constructor(name) {
this.persName = name;
}
myName() {
return "My name is " + this.persName;
}
}
function getPers(_perName, fullName) {
_personName = new Person(fullName);
}
$(document).ready(function() {
getPers(John, "John Doe");
});
You can follow the following exapmle. Please note there is not much logic init. The example is just to show you how OOP can work. Of cause, there are many other and better ways to got with that, but for the first try, it should be good to use.
class Person {
//declare the constructor with required name values and optional age value
constructor(firstName, lastName, age = 0) {
this.firstName = firstName;
this.lastName = lastName;
this.age = age;
}
//declare a typically setter, e.g. for age
setAge(age) {
this.age = age;
}
//declare a getter for the person with age
getPerson() {
return this.firstName + ' ' + this.lastName + ' is ' + this.age + ' years old.';
}
}
//here you got with some function within you need to define a new person
function getCreatedPerson(firstName, lastName, age = 0) {
//define the person with required firstname and lastname
const person = new Person(firstName, lastName);
//use the setter to set age of person
person.setAge(age);
//return the person by using the person getter
return person.getPerson();
}
//here you can call the createdPerson function
$(document).ready(function() {
console.log(getCreatedPerson('John', 'Doe', 32));
});
Hope it helps a bit to understand how it could work.
Yes, you can take the fullname as a parameter to your function and pass it through to the OOP method or constructor you're calling.
But you can't take a "reference to a variable" as an argument, like you tried with _perName/_personName. Instead, use the return keyword to return the created object:
function createPerson(fullName) {
return new Person(fullName);
}
$(document).ready(function() {
var john = createPerson("John Doe");
… // use john
});

Is there a way to define a prototype property with a reference to another property?

Let's say a simple prototype is defined:
function Person(firstName, lastName) {
this.firstName = firstName;
this.lastName = lastName
this.fullName = first + " " + last;
}
Now, I want to add a new property down the road called nickName. (but I don't want to use a method, that's already well documented)
Person.prototype.nickName = (what to put here to have firstName + first letter of lastName)
I used:
Person.prototype = {
get nickName(){
return this.firstName+ this.lastName.charAt(0);
}
};
But it doesn't work for already created Persons.
I just want to know if there is a way to do it, besides including it in the initial definition.
You can just add a new method to the prototype:
Person.prototype.nickname = function() {
return this.firstName + this.lastName.charAt(0);
}

Using Prototype of function constructor add new function

I want to check my idea is correct or not?
Codes:
function Person(firstname, lastname) {
this.firstname = firstname;
this.lastname = lastname;
}
Person.prototype.getFullName = function () {
return this.firstname + ' ' + this.lastname;
}
var john = new Person('Melo','Tang');
I call the code in the following picture "function constructor".
function Person(firstname, lastname) {
this.firstname = firstname;
this.lastname = lastname;
}
When the program run to this line
var john = new Person('Melo','Tang');
JS will use prototype chain to add the getFullName function in the "function constructor" Object and new a empty Object like following picture am I right?
I don't really understand what your diagram or the arrows or their colors are supposed to represent.
When the program runs to this line
var john = new Person('Melo','Tang');
What happens here is exactly that a new object is constructed via the Person constructor, with Person.prototype as its prototype. Other than being used as the prototype for the new object, Person.prototype is not examined or consulted, nor is anything done with the methods on it at this time. The prototype is consulted only when looking up properties and methods, such as when calling john.getFullName().
For clarity, I would avoid the term "function constructor object". Just call it a "constructor (function)".

properties on javascript protoype verses on object what's the difference? [duplicate]

This question already has answers here:
Use of 'prototype' vs. 'this' in JavaScript?
(15 answers)
Closed 6 years ago.
Take this example:
var personPrototype = {
firstName: '',
lastName: '',
getFullname: function() {
return this.firstName + ' : ' + this.lastName;
}
}
Person = {
};
function newPerson(firstName, lastName) {
var Person = function(firstName, lastName) {
this.firstName = firstName;
this.lastName = lastName;
}
Person.prototype = personPrototype;
return new Person(firstName, lastName);
}
var p1 = newPerson('someone', 'else');
var p2 = newPerson('john', 'doe');
console.log(p1.getFullname());
console.log(p2.getFullname());
Moving the firstName and lastName from the personPrototype to the Person yields the same results. Does that mean that there is no difference between the two, or am I overlooking something?
The difference between properties put directly on an object and properties put on the prototype of an object is quite significant. The prototype is shared by all instances of an object. Properties defined in the object (as in within a constructor function) will be defined on each instance.
I suspect that you are getting confused when defining your Person object. The Person in the global scope is being overridden by your constructor function inside newPerson and is never used. You don't need to define your properties at all outside of your constructor/method functions unless you have a specific reason to share a value between all instances of the object.
As for why defining the properties in the prototype makes no difference: it's the prototype chain. When you define firstName et al in personPrototype and then also in the constructor function it is overridden. So calling getFullName falls back to personPrototype and then looks for lastName on the current instance of Person thus picking up the value passed when you call new Person(firstName, lastName).

Return new object it built in Javascript

I am practicing Javascript object function. Supposed I have firstName and lastName as two arguments of my function.I want to display like this {"firstName":"tim","lastName":doe} . Here is my code but it printed out undefined. Any idea? Thank you!
function myFunction(firstName, lastName) {
this.name1 = firstName;
this.name2 = lastName;
}
var obj = new myFunction();
console.log(myFunction('tim', 'doe'));
Try this:
console.log(new myFunction('tim', 'doe'));
Or this:
console.log(obj);
You can try this
function myFunction(firstName, lastName) {
this.name1 = firstName;
this.name2 = lastName;
}
var obj = new myFunction('tim', 'doe');
console.log(obj);
You can see this documentation JavaScript Constructors
This kind of function called constructor, and you shouldn't call it directly. You have to use it with new.
console.log(new myFunction('tim', 'doe'));
This will print the result as you expect.
To distinguish the constructors from normal functions, it's better to name it begin with capital letter, like this:
function MyFunction(...) {...}
the undefined you receive is from the function not having a return value, see this post regarding that:Simple function returning 'undefined' value
to get the result you want...
function myFunction(firstName, lastName) {
this.name1 = firstName;
this.name2 = lastName;
}
var obj = new myFunction('tim', 'doe');
console.log(obj);
Let's explore what this line does: console.log(myFunction('tim', 'doe'));
This part: myFunction('tim', 'doe') executes myFunction as a function. Since myFunction does not have a return operator, it's return value is 'undefined' which is javascript's way of saying it doesn't exist. Thus, the word 'undefined' is printed on the console.
Additional tips:
Try adding this line: console.log(typeof myFunction);
This should print 'function'.
(May the 'typeof' operator become your best friend)
Try adding a return line as the last line of myFunctions such as:
return 'First name: ' + firstName + " Last name: " + lastName;
However, at this point the 'var obj = new myFunction();' line is unused.
Try adding another line:
console.log(typeof obj);
This should print 'object' which means that 'obj' is just that - an object.
Here is a complete example you can play with:
function myFunction(firstName, lastName) {
this.name1 = firstName;
this.name2 = lastName;
this.getNames = function() {
return 'First name: ' + firstName + " Last name: " + lastName;
}
console.log("This executes once upon instatiation (the line with var obj = new ...)");
return "Return value";
}
var obj = new myFunction('tim', 'doe');
console.log(typeof myFunction);
console.log(typeof obj);
console.log(obj.getNames());
Let me know if any of the above needs clarification. Good luck ...
BTW, this is what the output should look like on the console:
This executes once upon instatiation (the line with var obj = new ...)
script.js:14 function
script.js:15 object
script.js:16 First name: tim Last name: doe

Categories