javascript - 面向对象的 javascript - "this"关键字和对象内的访问函数

标签 javascript

我是第一次尝试一些 OO JS。这是我到目前为止的想法:

var myObj = {
1   site_url: window.location.protocol + "//" + window.location.hostname + "/",
2   site_host: window.location.hostname,
3   site_brand: this.readCookie('aCookieName'),
4   site_full_url: this.site_url + window.location.pathname,
5   /***
6   Read a cookie by its name;
7   **/
8
9   readCookie: function(name) {
10      var nameEQ = name + "=";
11      var ca = document.cookie.split(';');
12      for(var i=0;i < ca.length;i++) {
13          var c = ca[i];
14          while (c.charAt(0) == ' ') c = c.substring(1, c.length);
15          if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length);
16      }
17      return null;
18  },
19
20  /***
20  ***/
22  SaySomeThing: function() {
23      alert(this.site_brand);
24  }
}

请耐心等待,我是新手。我遇到的问题是:

第 3 行 - 我得到一个错误:readCookie 未定义;
第 4 行 - 另一个错误:site_url 未定义;

请帮我解决以上问题。

最佳答案

在javascript中,对象没有this的概念。

this 关键字的值在函数中由调用该函数的方式决定。

例如,在您的 myObj 中,如果您这样做:

myObj.readCookie('someName');

然后在 readCookie 函数中,this 将被设置为 myObj

如果你想让 site_brand 调用 readCookie 函数,那么你应该给 site_brand 自己的调用它的函数:

site_brand: function() { return this.readCookie('aCookieName'); },

...并这样调用它:

myObj.site_brand()

...因此 site_brand 函数中的 this 是对 myObj 的引用。


编辑:问题中的代码发生了一些变化(我认为是由于格式原因)。

答案是一样的,但我只是注意到在 SaySomeThing 函数中调用 this.site_brand 是可以的,只要 SaySomeThingmyObj 调用。

 // this is fine
SaySomeThing: function() {
   alert(this.site_brand);
}

 // as long as you're calling it something like
myObj.SaySomeThing();

关于javascript - 面向对象的 javascript - "this"关键字和对象内的访问函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4875770/

相关文章:

javascript - 如何移动 DOM 中的元素?

javascript - 如何使用带有数组的脚本将公式拖到 Google 电子表格中的右侧?

javascript - Medium-editor:如何应用多个标签包装器?

javascript - 如何设置由 javascript 动态创建的元素的样式

javascript - .load() 之后使用 JavaScript 和 jQuery 使用用户输入的值重置文本框

javascript - xmlhttprequest(xhr) 对象 xhr.onerror 和 xhr.upload.onerror 的区别

javascript正则表达式匹配带和不带数字的字符串

php - 从 html 链接调用 AS3 函数 - Javascript? PHP? swf地址?

javascript - 访问 razor block 中的本地 js 变量

javascript - 递归函数不以 return 语句结束?