LoginSignup
2
2

More than 5 years have passed since last update.

第9回つぶやき勉強会 ~ JS がどんどん楽しくなるクラス ~

Posted at
1 / 5

以前に ruby で書いたクラスサンプルを JS で書き直す問題を出しました。以下のようなものです。


rubyの場合
class Person
  def initialize(name)
    @name = name
  end
  def greet
    "My name is #{@name}"
  end
end

person = Person.new("Terada")
person.greet # => "My name is Terada"

従来のJavaScript
function Person(name){
  this.name = name
  this.greet = function(){ 
                 return "My name is " + this.name
               }
}
person = new Person("Terada");
person.greet(); // => "My name is Terada"

上を、ES2015からつかえる class 構文をつかって書き直してみます。


ES2015の場合
class Person {
  constructor(name) {
    this.name = name
  }
  greet() {
    return "My name is " + this.name
  }
}
const person = new Person("Terada")
person.greet()

どんどん楽しくなりますね。

2
2
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
2
2