Question about creating methods as Object properties


#1



The script below, in the area function, why is necessary to include this.radius in the return? The variable radius works without this.


function Circle (radius) {
    this.radius = radius;
    this.area = function () {
        return Math.PI * this.radius * this.radius;
        
    };
    // define a perimeter method here
    this.perimeter = function() {
        return 2 * Math.PI * radius;
    };
};


#2

Each time we create a new instance of the class, it has its own properties that stay with it. When a method is invoked, it is invoked ON the instance that owns it. The method is in the same scope as the instance variables but it accesses those variables with the this.prefix where this is the placeholder for the instance variable name.

    var rad_10 = new Circle(10);

    var rad_pi = new Circle(Math.PI);

    // this is 'rad_10'
    console.log(rad_10.area());        // 314.1592653589793

    // this is 'rad_pi'
    console.log(rad_pi.perimeter()):   // 19.739208802178716

this always refers to the context object that invokes the method.


#3

Thanks for spelling it out.


#4


@mtf, Im just now getting to the classes lesson and I think I have been confusing classes and objects. In the script below, if Person is the class and name & age are the properties, do name and age together = the object?


function Person(name,age) {
  this.name = name;
  this.age = age;
}


#5

No, they are what they are, properties of the instance object.

bob = new Person("Bob", 19);

Now bob is the object, an instance of the Person class.

console.log(bob)              // { name: 'Bob', age: 19 }
console.log(typeof bob)       // object
console.log(bob.constructor)  // [Function: Person]

#6

So bob is an instance of Person, with the properties name and age, that have values of 'bob' and 19?


#7

Yes, bob is an instance of Person, and properties 'bob.name' and 'bob.age' have values, "Bob" and 19, respectively.


#8

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