0
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

JSのオブジェクト指向 初心者覚書

Last updated at Posted at 2020-07-27

初心者のためのオブジェクト指向 JavaScript

function Person(name) {
  this.name = name;
  this.greeting = function() {
    console.log('Hi! I\'m ' + this.name + '.');
  };
}

コンストラクタ呼び出し

  • コンストラクタは、ES5 以前は、オブジェクトを作成し、初期化するための関数オブジェクトのこと
  • 定義したPersonコンストラクタを使ってPersonオブジェクトを作るには、 newキーワードを付けてコンストラクタを呼びだすコンストラクタES5以前
  • コンストラクタの中で this で参照していたのは、新しく作成されたオブジェクトそのもの
  • newを付けないで呼び出せば、当然ながらオブジェクトは作成されない
let person1 = new Person('Bob');
person1.name;
person1.greeting();

innerHTML

function Person(name){

      this.name = name;
      this.greeting  = function(){
        'Hi! I\'m' + this.name + '.';
      };
    }

    let person1 = new Person('AIAI');
    person1.name;
    person1.greeting();
    console.log(person1.name);//AIAI

    var textPage = document.getElementById('root').textContent;
    console.log(textPage);//aaa

    document.getElementById('root').textContent = person1.name;

     //intextPage = "アイウエオ";
    console.log(textPage);//aaa

[オブジェクトにプロパティを追加]

var user = {
  this.name = {
          'first': first,
          'last' : last
        };
};

user.country = "Japan";
user["prefecture"] = "Shizuoka";

console.log("user", user);

サンプルのコードを少しだけ改造

<!DOCTYPE html>
<html>
  <head>
    <meta charset="utf-8">
    <title>Object-oriented JavaScript class further exercises</title>
  </head>

  <body>

    <div id="personTxt"></div>

  </body>

    <script>
      function Person(first, last, age, gender, interests) {
        this.name = {
          'first': first,
          'last' : last
        };
        this.age = age;
        this.gender = gender;
        this.interests = interests;
        this.bio = function() {
          // First define a string, and make it equal to the part of
          // the bio that we know will always be the same.
          var string = this.name.first + ' ' + this.name.last + ' is ' + this.age + ' years old. ';
          // define a variable that will contain the pronoun part of
          // the second sentence
          var pronoun;

          // check what the value of gender is, and set pronoun
          // to an appropriate value in each case
          if(this.gender === 'male' || this.gender === 'Male' || this.gender === 'm' || this.gender === 'M') {
            pronoun = 'He likes ';
          } else if(this.gender === 'female' || this.gender === 'Female' || this.gender === 'f' || this.gender === 'F') {
            pronoun = 'She likes ';
          } else {
            pronoun = 'They like ';
          }

          // add the pronoun string on to the end of the main string
          string += pronoun;

          // use another conditional to structure the last part of the
          // second sentence depending on whether the number of interests
          // is 1, 2, or 3
          if(this.interests.length === 1) {
            string += this.interests[0] + '.';
          } else if(this.interests.length === 2) {
            string += this.interests[0] + ' and ' + this.interests[1] + '.';
          } else {
            // if there are more than 2 interests, we loop through them
            // all, adding each one to the main string followed by a comma,
            // except for the last one, which needs an and & a full stop
            for(var i = 0; i < this.interests.length; i++) {
              if(i === this.interests.length - 1) {
                string += 'and ' + this.interests[i] + '.';
              } else {
                string += this.interests[i] + ', ';
              }
            }
          }

          // finally, with the string built, we alert() it
          alert(string);
        };
        this.greeting = function() {
          return 'Hi! I\'m ' + this.name.first + '.';
        };
      };

      let person1 = new Person('Tammi', 'Smith', 32, 'neutral', ['music', 'skiing', 'kickboxing','music', 'skiing', 'kickboxing']);

      person1.bio();

      let person2 = Object.create(person1);
      person2.name;
      //person2.greeting();

      document.getElementById('personTxt').textContent = person2.greeting();

    </script>
</html>
0
1
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
0
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?