** Compare JavaScript objects with Ruby classes. ** **
class Fruits
  def initialize(name, color)
    @name = name
    @color = color
  end
  def info
    puts "#{@name}Is#{@color}is."
  end
end
apple = Fruits.new("Apple", "red")
apple.info
#Output result:The apples are red.
I will convert the above ruby description to the JavaScript description in my own way. (Please forgive me if there is a simpler description.) Methods in JavaScript are functions, so ...
const Fruits = function(name, color){ //Formal argument
  this.name = name //this.But@I want to see it as an alternative to.
  this.color = color
  this.getName = function(){ return this.name } //Return that could be omitted in ruby, an error will occur if omitted in JavaScript.
  this.getColor = function(){ return this.color }
} 
const apple = new Fruits('Apple', 'red') //Actual argument//Instance generation
console.log(`${apple.getName()}Is${apple.getColor()}is.`)  //console.logがputsの代替is.
             //instance.Call by function expression name.()If there is no, an error will occur.
//Output result:The apples are red.
However, the following description is possible in JavaScript.
const Fruits = function(name, color){
  this.name = name
  this.color = color
} 
const apple = new Fruits('Apple', 'red')
console.log(`${apple.name}Is${apple.color}is.`)
//Output result:The apples are red.
It is possible to output the value of the instance variable in the defined ruby outside the object. If you replace this with the description of ruby, you will use a getter, and it will be the following description.
class Fruits
  def initialize(name, color)
    @name = name
    @color = color
  end
  def name
    @name
  end
  def color
    @color
  end
end
apple = Fruits.new("Apple", "red")
puts "#{apple.name}Is#{apple.color}is."
#Output result:The apples are red.
That is all.
Thank you for watching until the end.
We would be grateful if you could point out any mistakes or lack of knowledge.
Recommended Posts