A few questions about how JavaScript works
Posted
by
KayoticSully
on Programmers
See other posts from Programmers
or by KayoticSully
Published on 2012-09-07T05:33:04Z
Indexed on
2012/09/07
9:49 UTC
Read the original article
Hit count: 227
I originally posted on Stack Overflow and was told I might get some better answers here.
I have been looking deeply into JavaScript lately to fully understand the language and have a few nagging questions that I can not seem to find answers to (Specifically dealing with Object Oriented programming. I know JavaScript is meant to be used in an OOP manner I just want to understand it for the sake of completeness).
Assuming the following code:
function TestObject()
{
this.fA = function()
{
// do stuff
}
this.fB = testB;
function testB()
{
// do stuff
}
}
TestObject.prototype = {
fC : function
{
// do stuff
}
}
What is the difference between functions fA
and fB
? Do they behave exactly the same in scope and potential ability? Is it just convention or is one way technically better or proper?
If there is only ever going to be one instance of an object at any given time, would adding a function to the prototype such as fC
even be worthwhile? Is there any benefit to doing so? Is the prototype only really useful when dealing with many instances of an object or inheritance?
And what is technically the "proper" way to add methods to the prototype the way I have above or calling TestObject.prototype.functionName = function(){}
every time?
I am looking to keep my JavaScript code as clean and readable as possible but am also very interested in what the proper conventions for Objects are in the language. I come from a Java and PHP background and am trying to not make any assumptions about how JavaScript works since I know it is very different being prototype based.
Also are there any definitive JavaScript style guides or documentation about how JavaScript operates at a low level?
Thanks!
© Programmers or respective owner