我是第一次尝试一些 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
是可以的,只要 SaySomeThing
从 myObj
调用。
// 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/