xxxxxxxxxx
// we create a function by typing the keyword " function" + Function's name and ( we add the parameter here )
// {
// the function body
// }
// we call the function by typing it's name without the keyword and we add ()
function second (name){
name = "Elmustafa";
alert(name);
}
first();
xxxxxxxxxx
function one(){
console.log('this is function one');
}
function two(){
one();
}
two();
xxxxxxxxxx
// Create a function (you decide the name) that logs out the number 42
// to the console
// Call/invoke the function
function number(){
console.log(42)
}
number()
//result = 42
xxxxxxxxxx
const personOne = {
firstName : "Elon",
secondName : "Musk"
}
const getFullName = function(company, country) {
console.log(this.firstName + " " + this.secondName + ", " + company + ", " + country);
}
const personTwo = {
firstName : "Mark",
secondName : "Zuckerburg"
}
getFullName.call(personOne, "Tesla", "United States"); // outputs Elon Musk, Tesla, United States
getFullName.call(personTwo, "Facebook", "United States"); // outputs Mark Zuckerberg, Facebook, United States
FunctionName.call(Object/function whose values you want to use as arguments for the 'this' in a function, arg1, arg2, ...argN), if your function needs to receive arguments, pass the arguments in place of ...arg.
xxxxxxxxxx
const car = {
name: 'car',
start() {
console.log('Start the ' + this.name);
},
speedUp() {
console.log('Speed up the ' + this.name);
},
stop() {
console.log('Stop the ' + this.name);
},
};
const aircraft = {
name: 'aircraft',
fly() {
console.log('Fly');
},
};
car.start.call(aircraft);
car.speedUp.call(aircraft);
aircraft.fly();
/*
// Outputs
Start the aircraft
Speed up the aircraft
Fly
*/
// With love @kouqhar
By default, the this inside the function is set to the global object i.e. window in the web browsers and global in Nodejs.
xxxxxxxxxx
function myFunc(p1, p2, pN)
{
// here "this" will equal "myThis"
}
let myThis = {};
// call myFunc using myThis as context.
// pass params to function arguments.
myFunc.call(myThis, "param1", "param2", "paramN");
xxxxxxxxxx
const person = {
firstName:"John",
lastName: "Doe",
fullName: function () {
return this.firstName + " " + this.lastName;
}
}
// This will return "John Doe":
person.fullName();
xxxxxxxxxx
const person = {
name: "John Smith",
getNameAndAddress: function(city, country)
{
return this.name+city+country;
}
}
const personWithoutGet = {
name: "Jerry Smithers"}
console.log(person.getNameAndAddress.call(personWithoutGet, 'Berlin','Germany'));
/*you can think of bind(), apply() and call() ALL as "stealing someone else's function to use."*/
/* victimBeingStolenFrom.functionName.call(theThief) */
/*notice the second variable personWithoutGet does not have a getName function*/
xxxxxxxxxx
l = "abcder";
q = "Ererwrwrewrew";
console.log(String.prototype.substr.call(q, 1, 4))
/*rerw...4 refers to how many characters to substring*/