Object literal notation alternative for consturctor


#1


https://www.codecademy.com/en/courses/spencer-sandbox/2/5?curriculum_id=506324b3a7dffd00020bf661


what is the object literal notation equivalent for the code below using "this"?

bob.setAge = setAge;


code using constructor:

// here we define our method using "this", before we even introduce bob
var setAge = function (newAge) {
  this.age = newAge;
};
// now we make bob
var bob = new Object();
bob.age = 30;
bob.setAge = setAge;       //************ this line ********************

bob.setAge(50);
console.log(bob.age);

code using object literal notation:

var setAge = function(newAge){
	this.age = newAge
}

var bob = {
	age: 30,
	????????????????????????  dont know how to do this line
}

bob.setAge(50);
console.log(bob.age);

I managed to do the following code, but cannot do it in the codes above

var square = {
	sideLength: 6,
	calcPerimether: function(){             //this line
		return this.sideLength * 4;     //this line
	},
	calcArea: function(){
		return Math.pow(this.sideLength, 2);
	},
}

var p = square.calcPerimether();
var a = square.calcArea();
console.log(p)
console.log(a)

var square = new Object();
square.sideLength = 6;
square.calcPerimeter = function() {         // this line
  return this.sideLength * 4;
};
square.calcArea = function() {                // this line
  return Math.pow(this.sideLength, 2);
};

var p = square.calcPerimeter();
var a = square.calcArea();

console.log(p)
console.log(a)

#2

// 1
var bob = {
  age: 30,
  setAge: function (newAge) {
     this.age = newAge;
  }
};

bob.setAge(50);
console.log(bob.age);

// 2
var setAge = function(newAge) {
   this.age = newAge
}

var bob = {
   age: 30,
   setAge: setAge
}

bob.setAge(50);
console.log(bob.age);

Is it clear for you?


#3

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