Qiita Teams that are logged in
You are not logged in to any team

Log in to Qiita Team
Community
OrganizationEventAdvent CalendarQiitadon (β)
Service
Qiita JobsQiita ZineQiita Blog
11
Help us understand the problem. What are the problem?

More than 5 years have passed since last update.

@ryokio0129

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

// 関数式でのクラス宣言
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
11
Help us understand the problem. What are the problem?