2
2

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.

javascript

Last updated at Posted at 2018-11-16

プロトタイプ 

  インスタンンスのようなもの

コンストラクタ

  new演算子を用いて、オブジェクトを生成することを想定した、「関数オブジェクト」


var Member = function(firstName, lastName){
  this.firstName = firstName;
  this.lastName = lastName;
  this.getName = function(){
   return this.lastName + '' + this.firstName;
  }
};

var men = new Member('けんた','やまだ');
document.writeln(men.getName());

やまだ けんた

rubyに置き換えるとこんなこと?

class Member

  def initialize(firstName, lastName)
    @firstName = firstName
    @lastName = lastName
  end

  def getName
   @firstName + @lastName
  end

end

puts member = Member.new('けんた','やまだ')
puts member

プロトタイプの目的

javascriptのインスタンスは、【インスタンス毎にメソッドをもつ】

1プロトタイプにすると、【rubyのクラスのような扱いができる】
2インスタンスの値を引き継げる!!(インスタンス変数もインスタンス毎)


var Member = function(){};

Member.prototype.sex = '';


var men1 = new Member();
var men2 = new Member();
document.writeln(men1.sex + '|' + men2.sex);
men2.sex ='';
document.writeln(men1.sex + '|' + men2.sex);

| |

var Member = function(firstName, lastName){
  this.firstName = firstName;
  this.lastName = lastName;
}


Member.prototype.getName = function(){
 return this.lastName + '' + this.firstName;
};

Member.prototype.toString = function(){
  return this.lastName + this.firstName;
}

Member.prototype.firstName =" AAA"

Member.prototype.lastName =" BBBB"

document.writeln(Member.prototype.getName())

document.writeln(Member.prototype.toString())


Member.prototype = {

getName : function(){
 return this.lastName + '' + this.firstName;
};

toString : function(){
  return this.lastName + this.firstName;
}
}


Member.prototype.getName = function(){
 return this.lastName + '' + this.firstName;
};

Member.prototype.toString = function(){
  return this.lastName + this.firstName;
}





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

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?