Consider this code:
function Foo() {
}
Foo.prototype.alert = function() {
alert(this);
}
(new Foo()).alert();
When executed (in jsfiddle), the alert shows that 'this' is the window object. Changing the last line to :
var foo = new Foo();
foo.alert();
works as expected.
Why is the difference?
5) Inline functions may not be useful for many embedded systems. Because in embedded systems code size is more important than speed. 6) Inline functions might cause thrashing because inlining might increase size of the binary executable file. Thrashing in memory causes performance of computer to degrade.
If a function is inline, the compiler places a copy of the code of that function at each point where the function is called at compile time. Normal functions do not have any such functionality. In case of inline function, function calling is replaced by that function definition.
inline functions might make it faster: As shown above, procedural integration might remove a bunch of unnecessary instructions, which might make things run faster. inline functions might make it slower: Too much inlining might cause code bloat, which might cause “thrashing” on demand-paged virtual-memory systems.
Inline Function in C++ The main advantage of inline functions is that you can use them with C++ classes as well. When an instruction of a function call is encountered during the compilation of a program, its memory address is stored by the compiler.
Your code is actually:
function Foo() {
}
Foo.prototype.alert = function() {
alert(this);
}(new Foo()).alert();
Because of the missing semicolon, add a semicolon and it will run properly.
It seems that you are missing a semi-colon:
function Foo() {
}
Foo.prototype.alert = function() {
alert(this);
}; //Semi-colon here!
(new Foo()).alert();
Here's a fiddle in which it appears to work as you expect.
What is actually happening is that the alert
method gets called immediately, with a new instance of Foo
passed into it, and alert
is then called on the return value (which is undefined
):
Foo.prototype.alert = function() {
alert(this);
}(new Foo()).alert();
As @Nemoy has mentioned, if you just use new Foo().alert()
you will get the expected behaviour because automatic semi-colon insertion will put a semi-colon in the right place for you (the lack of a semi-colon doesn't change the meaning of the code). And as the new
operator has the highest precedence, the parentheses are not required.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With