Javascript創建對象的5種姿勢

/* Start and stop animations using functions. */

function startAnimation() {
  alert('startAnimation');
}

function stopAnimation() {
  alert('stopAnimation');
}



/* Anim class. */

var Anim = function() {

};
Anim.prototype.start = function() {
    alert('dasdasd');
};
Anim.prototype.stop = function() {
  alert('dsadsasdfdsfds');
};

/* Usage. */

var myAnim = new Anim();
myAnim.start();
myAnim.stop();



/* Anim class, with a slightly different syntax for declaring methods. */

var Anim = function() { 

};
Anim.prototype = {
  start: function() {
    alert('i am start');
  },
  stop: function() {
    alert('i am stop');
  }
};

var myAnim = new Anim();
myAnim.start();
myAnim.stop();

/* Add a method to the Function class that can be used to declare methods. */

Function.prototype.method = function(name, fn) {
  this.prototype[name] = fn;
};

/* Anim class, with methods created using a convenience method. */

var Anim = function() { 

};
Anim.method('start', function() {
  alert('i am a start two');
});
Anim.method('stop', function() {
  alert(' i am a stop two');
});

var myAnim = new Anim();
myAnim.start();
myAnim.stop();

/* This version allows the calls to be chained. */

Function.prototype.method = function(name, fn) {
    this.prototype[name] = fn;
    return this;
};

/* Anim class, with methods created using a convenience method and chaining. */

var Anim = function() { 

};
Anim.
  method('start', function() {
   alert('endstart');
  }).
  method('stop', function() {
   alert('endstop');
  });

最後想說:

最近纔想着把自己這三年來學到的東西分享出來,技術是無邊界的,共享纔是趨勢!下面是我的個人公衆號,喜歡的朋友可以關注一下哈。

二維碼

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章