Cl*ss is in Session


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;


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


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


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);
// result is 4

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


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


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)


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


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..


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.


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