JS 改變執行環境(this指向)

  1. 創建.html文件
    引入jquery
	<input type="text" id="J_input" />
  1. 創建js文件
	var textCount = {
	  input: null,
	  getNum: 0,
	  init: function (config) {
	    this.input = $(config.id)
	    this.bindEvent();
	    return this;
	  },
	  bindEvent() {
	    var that = this;
	
	    /* // 方法一 應該是好多人一開始最喜歡用的,最省事的
	    this.input.on('keyup', function () {
	      that.render()
	    }); */
	
	    // 方法二  因爲bind仍然返回一個函數,所以在這裏可以這麼用
	    this.input.on('keyup', this.render.bind(this));
	
	    /*
	      // 方法 三  這個是jquery提供的方法(接受兩個參數,第一個是一個函數,第二個要改變成的執行環境)
	      this.input.on('keyup', $.proxy(function () {
	      this.render()
	    }, this)); */
	
	    /* // 方法 四  這個是jquery提供的方法 其實同上一個方法, 在這裏 this.render沒有加括號,標識引用這個函數而不是執行
	    this.input.on('keyup', $.proxy(this.render, this)); */
	
	    /* // 方法五 es6的箭頭函數
	    this.input.on('keyup',  () =>{
	      this.render()
	    }); */
	
	  },
	  render() {
	    this.getNumF();
	    if ($('#J_input_count').length == 0) {
	      this.input.after('<span id="J_input_count">' + this.getNum + '</span>');
	    }
	    $('#J_input_count').html(this.getNum + '個字');
	  },
	  getNumF() {
	    this.getNum = this.input.val().length || 0;
	  }
	}
	
	textCount.init({
	  id: "#J_input"
	}).render()
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章