Methods in JavaScript | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
- 1

Methods in JavaScript

Where am I going wrong? function myFirstMethod(line){ console.log("The name is " + this.name + "and the work is " + this.work + " " + line); } var object1 = {name : "ankit", work : "to be awesome"}; object1.myFirstMethod("yup, thats right"); Getting the following error: object1.myFirstMethod("yup, thats right"); ^ TypeError: object1.myFirstMethod is not a function

9th May 2017, 7:09 PM
Ankit Sahay
Ankit Sahay - avatar
7 Answers
+ 1
function myFirstMethod(line){ console.log("The name is " + this.name + "and the work is " + this.work + " " + line); } var object1 = {name : "ankit", work : "to be awesome", myFirstMethod:myFirstMethod}; object1.myFirstMethod("yup, thats right"); this is the answer, I was not defining myFirstObject in the object1
9th May 2017, 8:12 PM
Ankit Sahay
Ankit Sahay - avatar
+ 4
here is the answer; var object1 = {name : "ankit", work : "to be awesome"}; object1.myFirstMethod=function (line){ console.log("The name is " + this.name + "and the work is " + this.work + " " + line); } object1.myFirstMethod("yup, thats right");
9th May 2017, 7:46 PM
MR Programmer
MR Programmer - avatar
+ 2
both are same only difference is i declared the function outside.
9th May 2017, 7:52 PM
MR Programmer
MR Programmer - avatar
+ 2
just check your code inside var object1{ ..... myFirstMethod:myFirstMethod };
9th May 2017, 7:59 PM
MR Programmer
MR Programmer - avatar
+ 2
yes this is the ans
9th May 2017, 8:15 PM
MR Programmer
MR Programmer - avatar
0
I get what you did there, but then why does this version of the same code runs fine? function speak(line){ console.log("The "+this.type+" rabbitsays'"+line+"'"); } var whiteRabbit={type : "white", speak:speak}; whiteRabbit.speak("Oh my ear sand whiskers,"+"how late it's getting!");
9th May 2017, 7:50 PM
Ankit Sahay
Ankit Sahay - avatar
0
I get that, but why is my code, in the original question not running? when what i have provided in the next comment works?
9th May 2017, 7:57 PM
Ankit Sahay
Ankit Sahay - avatar