面向对象的javascript - “this”关键字和访问对象内的功能 [英] object oriented javascript - "this" key word and accessing functions within an object
问题描述
我是第一次尝试一些OO JS。这是我到目前为止所提出的:
I am, for the first time, trying some OO JS. Here is what I've come up with so far:
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 }
}
跟我说话,我是新来的。我遇到的问题是:
Bear with me, I am new to this. The problem I have is:
第3行 - 我收到错误:readCookie未定义;
第4行 - 另一个错误:site_url是undefined;
Line # 3 - I get an error: readCookie is undefined;
Line # 4 - Another error: site_url is undefined;
请帮我解决上述问题。
推荐答案
In javascript,一个对象没有这个
的概念。
In javascript, an object has no concept of this
.
这个<的值/ code>关键字在函数中通过如何确定该函数被确定。
The value of the this
keyword is determined in a function by how that function is called.
例如,在你的 myObj
中,如果你这样做:
For example, in your myObj
, if you do:
myObj.readCookie('someName');
然后在 readCookie
函数内,此
将设置为 myObj
。
Then inside the readCookie
function, this
will be set to myObj
.
如果你想 site_brand
调用 readCookie
函数,然后你应该给 site_brand
它自己的函数调用它:
If you want site_brand
to call the readCookie
function, then you should give site_brand
its own function that calls it:
site_brand: function() { return this.readCookie('aCookieName'); },
...并称之为:
myObj.site_brand()
...所以这个
里面的 site_brand
函数是对 myObj
。
...so that this
inside the site_brand
function is a reference to myObj
.
编辑:问题中的代码有所改变(由于格式化问题)认为)。
The code in the question changed a bit (due to formatting I think).
答案是一样的,但我只是注意到在中调用
, this.site_brand
只要从 myObj
SaySomeThing SaySomeThing
就可以了。 >。
The answer is the same, but I'd just note that calling this.site_brand
in the SaySomeThing
function is fine as long as SaySomeThing
was called from myObj
.
// this is fine
SaySomeThing: function() {
alert(this.site_brand);
}
// as long as you're calling it something like
myObj.SaySomeThing();
这篇关于面向对象的javascript - “this”关键字和访问对象内的功能的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!