我是第一次尝试一些OO JS.这是我到目前为止所提出的: var myObj = {1 site_url: window.location.protocol + "//" + window.location.hostname + "/",2 site_host: window.location.hostname,3 site_brand: this.readCookie('aCookieN
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关键字的值在函数中根据函数的调用方式确定.
例如,在你的myObj中,如果你这样做:
myObj.readCookie('someName');
然后在readCookie函数中,这将被设置为myObj.
如果你想让site_brand调用readCookie函数,那么你应该给site_brand一个自己调用它的函数:
site_brand: function() { return this.readCookie('aCookieName'); },
……并称之为:
myObj.site_brand()
…这样在site_brand函数内部就是对myObj的引用.
编辑:问题中的代码有点改变(由于我认为格式化).
答案是一样的,但我只是注意,只要从myObj调用SaySomeThing,在SaySomeThing函数中调用this.site_brand就可以了.
// this is fine SaySomeThing: function() { alert(this.site_brand); } // as long as you're calling it something like myObj.SaySomeThing();