This is a code the works fine in Codecademy which is where it's from. However, when I try the same code in the browser, it keeps returning undefined.
<script>
function Cat(name, breed) {
this.name = name;
this.breed = breed;
}
Cat.prototype.meow = function() {
console.log('Meow!');
};
var cheshire = new Cat("Cheshire Cat", "British Shorthair");
var gary = new Cat("Gary", "Domestic Shorthair");
alert(console.log(cheshire.meow));
alert(console.log(gary.meow));
</script>
You're passing the result of console.log() to alert but it doesn't return anything so you're passing undefined to alert.
Either use only alert or only console log, don't pass one to the other.
Your meow function already logs to the console, so doing it again is pointless. Most likely what you want is this:
cheshire.meow();
gary.meow();
Note that since meow is a function, you probably want to actually call it and not just print the function itself.
Related
I'm new to JavaScript, and I try to play around with it to understand all in-and-outs. I write
function greet() {
console.log("Hi");
};
console.log(greet());
And the result of it in the console is
> Hi app.js:2
> undefined app.js:4
I assume this is because greet() inside console.log first calls the function, which prints out "Hi". We get first line of log. But where did the second line come from?
Then I thought because Hi is overall result of greet(), then console.log basically calls variable Hi, but in this case the result would be is not defined, not undefined
In JavaScript, if nothing is returned from the function with the keyword return then undefined is returned by default.
var data = greet();
console.log(data);// undefined, since your function does not return.
Is equivalent to:
console.log(greet());
The second output is the returned result from the function. Since you are not returning anything from the function hence prints undefined.
To print 'Hi' in the second console you have to return that from the function.
function greet() {
console.log("Hi");
return 'Hi';
};
console.log(greet());
You should use a return keyword like this:
function greet() {
console.log("HI");
return "HI";
};
console.log(greet());
Or you can store it in a variable and return the variable:
function greet() {
const hello = ("HI");
return hello;
};
cosnole.log(greet());
,Because if you don't use return keyword and log the function to the console then it returns undefined.
function Person(name,age){
this.name=name;
this.age=age;
}
var person1 = new Person("name1",4)
var person2 = new Person("name2",6)
function Animal(name,size){
this.name=name;
this.size=size;
}
var animal1=new Animal("name1","small")
var animal2 = new Animal("name2","big")
Person.prototype.sayName=function(){
console.log("Hello "+[name])
}
Animal.prototype.sayName=function(){
console.log("Hello "+[name])
}
animal1.sayName();
I just learned Javascript and I started playing around with some code. When I run this code, the console prints out undefined. I believe the console should print : "Hello animal1". What is wrong with it?
In javascript, when you say new, first thing that would happen is that an empty object would be created. Upon the creation of this object, the animal function is executed and the current execution context would be referring to newly created empty object. So when you say this.name = name and this.size = size, the this keyword would be referring to the newly created object. So you need to always reference the property with this, while accessing it as shown in the below snippet:
function Animal(name,size){
this.name=name;
this.size=size;
}
var animal1=new Animal("name1","small")
Animal.prototype.sayName=function(){
console.log("Hello "+this.name)
}
animal1.sayName();
Hope this answers your question
you have to specify the this keyword to refer to the current instance.
Animal.prototype.sayName = function(){
console.log("Hello "+ this.name)
}
console.log("Hello " + [name]) should be console.log("Hello " + this.name)
I tried it in my console, now it outputs Hello name1.
for my own personal improvement, I was fiddling with closures and functions in JS, when I found this behaviour that deeply puzzles me.
Take this function, assign it to a variable, and call it from two different HTML elements via jQuery:
var print = function(){
console.log("Hello" );
};
document.getElementById('element1').onclick = print();
document.getElementById('element1').onclick = print;
Why on earth is the second element, if clicked, to be the one that prints correctly "hello"?
I always thought you need to put brackets after a function's name to call it.
In fact, if I just call the function by itself (and not via a jQuery event) it works as expected:
var print = function(){
console.log("Hello" );
};
print; //does nothing
print() //prints "Hello"
What I am missing here? Is something related to jQuery?
Thanks in advance!
The difference is calling a function vs taking a reference to a function.
The syntax func() immediately calls the function provided. In element.onclick = func(), the event will be bound to the return value of func.
With element.onclick = func, you are not calling func, simply referencing it and assigning it to the event.
If func happened to return a function, then you could use the element.onclick = func() syntax, and it would do what you expect.
document.getElementById('element1').onclick = print(); // Assigns the *return value* of print
document.getElementById('element1').onclick = print; // Assigns print
function returnPrinter() {
return function print() {
// do stuff
}
}
document.getElementById('element1').onclick = returnPrinter(); // Assigns the return value, which is a function, thus doing what you want
(Too long for comment.)
If you really want to mess with your own head:
var print = function() {
return function() {
console.log("Hello");
};
};
document.getElementById('element1').onclick = print();
This will do what you expect, but perhaps not why you expect it to.
Using
document.getElementById('element1').onclick = print();
is equivalent to the value returned from print (but there is no returned value, so it is undefined)
document.getElementById('element1').onclick = undefined;
When the onclick event handler is called, it calls the assigned value expecting a function. undefined() will also give you the same error. print() will do what you were expecting, and that is why when you use this it works
document.getElementById('element1').onclick = print;
A function is just like any other variable, except it has an additional operator:
Just like with objects and arrays, you can use the dot and square-brace operators to retrieve their properties, you can use the call operator to call the function, but that function is still a variable nevertheless.
function a() {
console.log("potato");
}
var b = a;
b() //prints "potato" on the console
On your example, using the print function on its own (without the call operator did nothing, but that would be the same as if you wrote a number on its own: the result is the value itself!
console.log(a); //prints function a()
console.log(42); //prints 42
When you type a something on its own line, it's just going to return that value to the expression, but without anything to do, nothing happens:
a; //nothing happens
42; //nothing happens
Now, when you use the call operator, it runs your function and the expression's value is whatever the function returned, or undefined if it didn't return anything.
function doStuff() {
return "potato";
}
Now suppose you have this expression:
console.log(doStuff());
It will run doStuff, and return to the expression:
console.log("potato");
Then it will run console.log, with "potato" as its parameter, and it will do its magic to show on the console.
Events are just like that, saving a function to a variable to use later:
function doom() {
return Infinity / 0;
}
onDoomsday = doom;
//somewhere else in your code:
onDoomsday(); //destroys the world
you have to bind reference of a function to onclick but in first case you actually doing nothing other than calling a function:
document.getElementById('element1').onclick = print();
It will actually invoke the function print() and since function has nothing in return so it will not impact on element1 click event.
on the other hand
document.getElementById('element1').onclick = print;
In order to make first case working you need to return a function so it can be invoked on event:
var print = function() {
// when this will invoke it will return function
return function() {
console.log("Hello");
};
};
will assign reference of function to onclick event and it invoke the function on each click event.
I am learning js and am confused on one thing. I am just copying/pasting the code example from mdn...
function Person(gender) {
this.gender = gender;
}
Person.prototype.sayGender = function() {
alert(this.gender);
};
var person1 = new Person('Male');
var genderTeller = person1.sayGender;
person1.sayGender(); // alerts 'Male'
genderTeller(); // alerts undefined
alert(genderTeller === person1.sayGender); // alerts true
alert(genderTeller === Person.prototype.sayGender); // alerts true
in the example above genderTeller will return undefined but after slightly modifying it in the second example:
function Person(gender) {
this.gender = gender;
}
Person.prototype.sayGender = function() {
alert(this.gender);
};
var person1 = new Person('Male');
var genderTeller = person1.sayGender();
genderTeller();
the genderTeller function actually works but also returns 'typeError: genderTeller is not a function.'
Why is genderTeller not a function in the second example when it's clearly assigned to a method?
In the first example, you are assigning a function to a variable and executing it. The this in that case is window, since you are just calling the function and not calling it on anything.
In the second case, you are invoking the function and assigning its result to genderTeller. Since the function doesn't return anything, the variable is undefined.
Look at this line:
var genderTeller = person1.sayGender();
You are assigning the value returned by calling the function since you are executing it, not the function itself.
Since the function doesn't actually return a value, it's not a function (or anything at all, really), which is why you are getting that error.
I thought I understood the concept of the JavaScript prototype object, as well as [[proto]] until I saw a few posts regarding class inheritance.
Firstly, "JavaScript OOP - the smart way" at http://amix.dk/blog/viewEntry/19038
See the implementation section:
var parent = new this('no_init');
And also "Simple JavaScript Inheritance" on John Resig's great blog.
var prototype = new this();
What does new this(); actually mean?
This statement makes no sense to me because my understand has been that this points to an object and not a constructor function. I've also tried testing statements in Firebug to figure this one out and all I receive is syntax errors.
My head has gone off into a complete spin.
Could someone please explain this in detail?
In a javascript static function, you can call new this() like so,
var Class = function(){}; // constructor
Class.foo = function(){return this;} // will return the Class function which is also an object
Therefore,
Class.foo = function(){ return new this();} // Will invoke the global Class func as a constructor
This way you get a static factory method. The moral of the story is, not to forget functions are just like any other objects when you are not calling them.
What is confusing you, I think, is just where "this" is really coming from. So bear with me-- here is a very brief explanation that I hope will make it quite clear.
In JavaScript, what "this" refers to within a function is always determined at the time the function is called. When you do:
jimmy.nap();
The nap function (method) runs and receives jimmy as "this".
What objects have references to nap is irrelevant. For example:
var jimmy = {}, billy = {};
jimmy.nap = function(){ alert("zzz"); };
var jimmy_nap = jimmy.nap;
jimmy_nap(); // during this function's execution, this is *NOT* jimmy!
// it is the global object ("window" in browsers), which is given as the
// context ("this") to all functions which are not given another context.
billy.sleep = jimmy.nap;
billy.sleep(); // during this function's excution, this is billy, *NOT* jimmy
jimmy.nap(); //okay, this time, this is jimmy!
In other words, whenever you have:
var some_func = function(arg1, arg2){ /*....*/ };
// let's say obj and other_obj are some objects that came from somewhere or another
obj.some_meth = some_func;
other_obj.some_meth = some_func;
obj.some_meth(2, 3);
other_obj.some_meth(2, 3);
What it's getting "translated" into (not literally-- this is pedagogical, not about how javascript interpreters actually work at all) is something like:
var some_func = function(this, arg1, arg2){ /* ...*/ };
// let's say obj and other_obj are some objects that came from somewhere or another
obj.some_meth = some_func;
other_obj.some_meth = some_func;
obj.some_meth(obj, 2, 3);
other_obj.some_meth(other_obj, 2, 3);
So, notice how extend is used in the example on that page:
UniversityPerson = Person.extend({ /* ... */ });
Pop quiz: When extend runs, what does it think "this" refers to?
Answer: That's right. "Person".
So the puzzling code above really is the same as (in that particular case):
var prototype = new Person('no_init');
Not so mysterious anymore, eh? This is possible because unlike in some languages,
a JavaScript variable-- including "this"-- can hold any value, including a function such as Person.
(There is nothing that makes Person specifically a constructor. Any function can be invoked with the new keyword. If I recall the exact semantics, I think they are that when a function is called with the new keyword, it is automatically given an empty object ({}) as its context ("this") and when the function returns, the return value is that same object unless (maybe?) the function returns something else)
This is a cool question because it speaks to a pretty essential part of JavaScript's neatness or oddness (depending on how you see it).
Does that answer your question? I can clarify if necessary.
AJS.Class effectively* translates this:
var Person = new AJS.Class({
init: function(name) {
this.name = name;
Person.count++;
},
getName: function() {
return this.name;
}
});
Person.count = 0;
into this:
var Person = function (name) {
this.name = name;
Person.count++;
};
Person.prototype = {
getName: function() {
return this.name;
}
};
Person.extend = AJS.Class.prototype.extend;
Person.implement = AJS.Class.prototype.implement;
Person.count = 0;
Therefore, in this case, this in AJS.Class.prototype.extend refers to Person, because:
Person.extend(...);
// is the same as
Person.extend.call(Person, ...);
// is the same as
AJS.Class.prototype.extend.call(Person, ...);
* There are a lot of cases I don't go over; this rewrite is for simplicity in understanding the problem.
Imagine the following situation :
var inner = function () {
var obj = new this;
console.log(obj.myProperty);
};
var f1 = function () {
this.myProperty = "my Property"
}
f1.f2 = inner;
f1.f2();
Here the calling object is itself a function, so this will return a function, and we can instantiate it.
In order to use this()(not this) the outer function(the context) must itself return smth that can be instantiated(another function):
var inner = function () {
var obj = new this();
console.log(obj.myProperty);
};
var f1 = function () {
var func = function () {};
func.myProperty = 'my property';
return func;
};
f1.f2 = inner;
f1.f2();
A simpler code explaination:
class User {
constructor() {
this.name = '';
this.age = '';
}
static getInfo() {
let user = new this();
console.log(user);
}
}
User.getInfo()
Output:
Object {
age: "",
name: ""
}
see this link http://www.quirksmode.org/js/this.html It will tell you about the this keyword, but I am not sure what this() is, may be its some kind of user defined function...... that you are not aware of...
"this" means the context of the function currently running.
The code you are posting surely appears in a function that act as a method for an object.
So the object is the context of the function.
"new this()" will return a clone of the current object after running its constructor function with the passed arguments.
this() refers to the the function that the code is in, but this() would have to be within that function. Calling new this(); within a function would create a never ending loop. Calling it outside of a function would be redundant because there is no function/class set as this().