Help us understand the problem. What is going on with this article?

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

More than 5 years have passed since last update.
// 関数式でのクラス宣言
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になってしまうようです。
むむむ…。

Why not register and get more from Qiita?
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away
Comments
No comments
Sign up for free and join this conversation.
If you already have a Qiita account
Why do not you register as a user and use Qiita more conveniently?
You need to log in to use this function. Qiita can be used more conveniently after logging in.
You seem to be reading articles frequently this month. Qiita can be used more conveniently after logging in.
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away
ユーザーは見つかりませんでした