LoginSignup
11
11

More than 5 years have passed since last update.

【メモ】クラス作る際の関数式と関数文での違い

Last updated at Posted at 2014-02-12
// 関数式でのクラス宣言
var Hoge = function(){};
Hoge.prototype = {
  foo: 'foo',
  getFoo: function(){
    return this.foo;
  }
};

// 関数文でのクラス宣言
function Piyo(){
  this.bar = 'bar';
  this.getBar = function(){
    return this.bar;
  };
}

console.log(Hoge.name);               // ""
console.log((new Hoge).constructor);  // function Object(){ [native code] }

console.log(Piyo.name);               // "Piyo"
console.log((new Piyo).constructor);  // function Piyo(){}

// 関数文でのクラス宣言
function Piyo(){}
Piyo.prototype = {
  bar: 'bar',
  getBar: function(){
    return this.bar;
  }
};
console.log( (new Piyo).constructor );  // function Object() { [native code] }

関数文と関数式、コンストラクタで宣言とprototypeで宣言で色々違うみたいです。
ここも違うんだ、と思ったのでメモ。


追記:

var Piyo = function(){};
Piyo.prototype = {};

console.log( (new Piyo).constructor ==  (function(){}) );  // false
console.log( (new Piyo).constructor === (function(){}) );  // false
console.log( (new Piyo).constructor === Piyo );            // true

constructorは比較できます。できないと困る。


追記2:

var Piyo = function(){
  this.foo = 1;
};
Piyo.prototype = {
  bar: 1,
  setBar: function(val){
    this.bar = val;
  }
};

var piyo = new Piyo();

// hasOwnProperty()メソッド
console.log( piyo.hasOwnProperty('foo') );  // true
console.log( piyo.hasOwnProperty('bar') );  // false

// in演算子
console.log( 'foo' in piyo );  // true
console.log( 'bar' in piyo );  // true

piyo.setBar('barbar');

// hasOwnProperty()メソッド
console.log( piyo.hasOwnProperty('bar') );  // true

prototypeで宣言しただけのプロパティはhasOwnProperty()だとfalseになってしまうようです。
むむむ…。

11
11
3

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
11
11