Cl*ss is in Session


#1

Can someone explain to me why code 1 is right and code 2 is wrong?

code 1

function Circle(radius) {
    this.radius = radius;
}

code 2

function Circle(radius) {
    radius = this.radius;
}

#2

How do you think what result should be with code 2?


#3

I don't know. Code 2 threw an error and I don't understand why.


#4

radius is a parameter for function-constructor Circle, so you can't assign it with property.
Code 1

function Circle(radius) {
    this.radius = radius;
}

means that you can create object and assign some value for radius property:

var circle = new Circle(4);
console.log(circle.radius);
// result is 4

So, we have object circle which has one property assigned to 4.


#5

Code 1 is the best practice.
Code 2 Javascript will assume radius is the property while this.radius is the value, which should be the opposite.
Please, try and read about Javascript best practices


#6

but this.radius is undefined, so its wrong. Yes, it can be useful, but not in this case.

code1 you create an instance variable (this.radius) and give it a value of radius (your function parameter)

code2 you create a member variable (radius) and give it a value of this.radius (which is a undefined instance variable, so it gives an error)


#7

I think that code 1 is a right way to create Object Constructor, code 2 is not correct at all.


#8

this.radius is undefined and that's why its throwing an error. You said according to the design of the programming, yeah.. my answer is according to the user's code and that's why am talking about best practices..


#9

I edited my answer, both are possible (be it for different purposes), so it has to do with what you want to achieve, not best practice.


#10

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.