Can anyone tell me if the following example classes are equivalent, with respect to the class properties. One is defined within the constuctor and one outside.
Example 1
function Test(input)
{
this.output = input ;
Test.WELCOME = "Hello ;
}
Example 2
function Test(input)
{
this.output = input ;
}
Test.WELCOME = "Hello ;
I have been using the second type but both seems to work.
Cheers
Can anyone tell me if the following example classes are equivalent, with respect to the class properties. One is defined within the constuctor and one outside.
Example 1
function Test(input)
{
this.output = input ;
Test.WELCOME = "Hello ;
}
Example 2
function Test(input)
{
this.output = input ;
}
Test.WELCOME = "Hello ;
I have been using the second type but both seems to work.
Cheers
Share Improve this question edited Nov 30, 2011 at 11:31 ZosoOfZep asked Nov 30, 2011 at 11:25 ZosoOfZepZosoOfZep 511 silver badge4 bronze badges 4- Related: Class keyword in Javascript. Zoso - Where is this JavaScript running? (probably not a browser) – Kobi Commented Nov 30, 2011 at 11:28
-
unless you are in some very early ES.Next alpha engine, there is no used
class
keyword in javascript. – jAndy Commented Nov 30, 2011 at 11:28 - sorry mistyped class should have been function. These are simulated classes not true class. – ZosoOfZep Commented Nov 30, 2011 at 11:32
- 1 @Kobi Ahh, interesting! Cool. – Pekka Commented Nov 30, 2011 at 11:35
2 Answers
Reset to default 4I'm pretty sure neither of those does what you really want it to do. The usual way this
inside of Test
is something useful will be when instantiating it using new
. Setting a property on Test
itself doesn't have any effect on objects created from it using x = new Test('someinput')
. What you would want to do is Test.prototype.WELCOME = 'Hello'
and instances of Test
would have that property in their [[proto]]
tree and then be able to make use of it.
function Test(input){
this.output = input;
}
Test.prototype.WELCOME = 'Hello';
var instanceOfTest = new Test('whatever');
// produces this structure:
instanceOfTest => {
output: 'whatever',
__proto__: {
WELCOME: 'Hello'
}
}
console.log(instanceOfTest.WELCOME); // 'Hello'
Assuming you mean:
function Test(input)
{
this.output = input;
Test.WELCOME = "Hello";
}
Example 2
function Test(input)
{
this.output = input ;
}
Test.WELCOME = "Hello";
Then there will be no difference in terms of the properties of any new Test
objects, however in Example 1 you will be assigning a WELCOME
property to the Test
function on each call to the method, whereas in Example 2 you will only assign this property once.