- 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
7 Respostas
+ 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
+ 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");
+ 2
both are same only difference is i declared the function outside.
+ 2
just check your code
inside
var object1{
.....
myFirstMethod:myFirstMethod
};
+ 2
yes this is the ans
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!");
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?