在读《JavaScript设计模式》的时候对这段代码有个疑问?
高洛峰
高洛峰 2017-04-10 14:52:06
[JavaScript讨论组]

书中讲单体模式用了这段代码。我的问题是在对象内部访问对象的属性时为何没有用this.foo而依然用GiantCorp.RegPage.foo

GiantCorp.RegPage = {

  // Constants.
  FORM_ID: 'reg-form',
  OUTPUT_ID: 'reg-results',

  // Form handling methods.
  handleSubmit: function(e) {
    e.preventDefault(); // Stop the normal form submission.

    var data = {};
    var inputs = GiantCorp.RegPage.formEl.getElementsByTagName('input');

    // Collect the values of the input fields in the form.
    for(var i = 0, len = inputs.length; i < len; i++) {
      data[inputs[i].name] = inputs[i].value;
    }

    // Send the form values back to the server.
    GiantCorp.RegPage.sendRegistration(data);
  },
  sendRegistration: function(data) {
    // Make an XHR request and call displayResult() when the response is
    // received.
    ...
  },
  displayResult: function(response) {
    // Output the response directly into the output element. We are
    // assuming the server will send back formatted HTML.
    GiantCorp.RegPage.outputEl.innerHTML = response;
  },

  // Initialization method.
  init: function() {
    // Get the form and output elements.
    GiantCorp.RegPage.formEl = $(GiantCorp.RegPage.FORM_ID);
    GiantCorp.RegPage.outputEl = $(GiantCorp.RegPage.OUTPUT_ID);

    // Hijack the form submission.
    addEvent(GiantCorp.RegPage.formEl, 'submit', GiantCorp.RegPage.handleSubmit);
  }
};

// Invoke the initialization method after the page loads.
addLoadEvent(GiantCorp.RegPage.init);
高洛峰
高洛峰

拥有18年软件开发和IT教学经验。曾任多家上市公司技术总监、架构师、项目经理、高级软件工程师等职务。 网络人气名人讲师,...

全部回复(2)
巴扎黑

可能是因为后面使用addLoadEvent调用导致的,在addLoadEvent函数内必然有这样的调用

javascriptfunction addLoadEvent(callback){
    callback();
}

这样的addLoadEvent里调用的GiantCorp.RegPage.foo,会让其this变成window,所以在函数里面this.foo不等于GiantCorp.RegPage.foo,必须要写全。

高洛峰

我同意ls的说法,this确实令人很头疼的问题。
下面我简单改造一下代码,做一番测试

var GiantCorp = window.GiantCorp || {};
GiantCorp.RegPage = {

  // Constants.
  FORM_ID: 'reg-form',
  OUTPUT_ID: 'reg-results',

  // another method, print
  print: function() {
       console.log(this.OUTPUT_ID);
  }
};

GiantCorp.RegPage.print(); // output 'reg-results'

var myObject = {
  OUTPUT_ID: 'my-results'
};
GiantCorp.RegPage.print.call(myObject); // output my-results

可见在这种情况下使用this也不是安全的。

热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板
关于我们 免责申明 举报中心 意见反馈 讲师合作 广告合作 最新更新 English
php中文网:公益在线php培训,帮助PHP学习者快速成长!
关注服务号 技术交流群
PHP中文网订阅号
每天精选资源文章推送
PHP中文网APP
随时随地碎片化学习

Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号