English 中文(简体)
理解 JavaScript OOP
原标题:Understanding JavaScript OOP

这真是我第一次和JavaScript一起上头等课, 我数月来一直学习如何使用JQuery, 这样我并不难教。在这个代码中,我会问很多问题。

OK,这是密码,我第一流口音课

window.myclass = function(){
    this.n1 = 0;
    this.n2 = 0;
    this.ans = 0;
    this.hehe = 0;

    this.defaultNumbersAdd = function(){

       this.hehe =setInterval(function(){
          //just an example of inert function...
          //the truth is i can t grab the this.n1 and this.n2...
          this.ans = this.n1 + this.n2;
       },100);
       clearTimeout(this.hehe);
    };

    this.returnAns = function(){
       return this.ans;
    };

    this.getAnswer = function(){
        this.defaultNumbersAdd(); //i want to reuse this function but I can t access it
        return this.returnAns(); //and also this one
    };

    this.modifynumbers = function(n1,n2){
        this.n1 = n1;
        this.n2 = n2;
    };
};

var myclassins = new window.myclass();
alert(myclassins.getAnswer);

现在我的问题是

1) 我如何抓取要在我的函数中使用的类变量( 此. vars) 。

2) 如何在另一个函数内使用其他函数

对不起,如果我的解释有点模糊...

最佳回答

this 指针直接在窗口中。 我的类对象指向该对象本身, 您正在使用它来定义该对象的本质属性, 如 n1 和 n2 。

然而,在您对象定义的函数范围内, this 指针指向函数,而不是对象。 *** 但是,在设置超时和设置 Intervals 中,“ this”关键字指向窗口对象或全球范围。 (见底端更新,例如。 )

因此,您可以直接访问属性, 使用您用来对类别进行即时处理的全局范围的变量名称,

    this.returnAns = function(){
       return myclassins.ans;
    };

然而,上述方法将您的类与在即时时间给对象的命名联系起来,并且仅适用于单个对象。

更好的解决办法是定义对象内的变量,并引用“此”指针:

window.myclass = function(){
    this.n1 = 0;
    this.n2 = 0;
    this.ans = 0;
    this.hehe = 0;
    var _self = this;   // reference to "this"

    this.defaultNumbersAdd = function(){

       myclass.hehe =setInterval(function(){
          //just an example of inert function...
              //the truth is i can t grab the this.n1 and this.n2...
          _self.ans = _self.n1 + _self.n2;
          console.log(_self.ans);
       },100);
       clearTimeout(_self.hehe);
    };

    this.returnAns = function(){
       return _self.ans;
    };

    this.getAnswer = function(){
        this.defaultNumbersAdd(); //i want to reuse this function but I can t access it
        return _self.returnAns(); //and also this one
    };

    this.modifynumbers = function(n1,n2){
        _self.n1 = n1;
        _self.n2 = n2;
    };
};

最后,另一种技术是使用关闭来定义函数,将“此”指针传递到返回另一个函数的函数,例如:

    this.modifynumbers = (function(__this) {
        return function(n1,n2){
            __this.n1 = n1;
            __this.n2 = n2;
        }
    })(this);

当然,最不复杂的方法是使用var self ;然而,在JavaScript,有几种不同的方法来完成一项任务,这些技术在不同的情景下可以证明是有用的。

UPDATE:

@apsillers指出,“此关键字”指向窗口对象时, 指向由设置Timeout 和设置 Interval 函数所引用的回调中引用的窗口对象。 以下是一个例子:

// top level scope
var global = "globalvalue";

window.demo = function() {
    this.somevar = "somevalue";        

    this.someFunct = function() {
        console.info("somevar = " + this.somevar);  // prints "somevalue"
        console.info("global = " + this.global);   // prints undefined! this points to "demo"!

        setTimeout( function() {
            console.info("timeout - somevar = " + this.somevar);  // undefined! references the "window" context
            console.info("timeout - global = " + this.global);   // prints "globalvalue"
        },1000);
    };
};
var dem = new demo();

dem.somevar;   // accessible from outside the object. prints "somevalue"
dem.someFunct();

< 强度 > 某些功能输出 () :

# inside method of object
somevar = somevalue
global = undefined

# inside timeout
timeout - somevar = undefined
timeout - global = globalvalue

正如你可以看到的那样,在设定时间外,“这个”明确指向窗口或全球范围! (注:你可以拿下那个小代码片,然后在您的 Chrome 或 Firebug 调试器中运行。)

问题回答

您可以使用 < a href=> 中描述的模块模式。 http:// daddyosmani. com/resources/quiminjsdesdesigntaptrists/book/" rel=“ no follow” > 这篇文章 。 使用该模块模式的好处在于您可以拥有私人变量, 并且只披露您想要公开的变量 。

var Myclass = (function(){

    var

    // Private
    n1 = 0,
    n2 = 0,
    ans = 0,
    hehe = 0,

    defaultNumbersAdd = function(){
       hehe = setInterval(function(){
          this.ans = this.n1 + this.n2;
       },100);
       clearTimeout(hehe);
    },

    returnAns = function(){
       return ans;
    },

    getAnswer = function(){
        this.defaultNumbersAdd();
        return returnAns()    
    },

    modifynumbers = function(n1 ,n2){
        n1 = n1;
        n2 = n2;
    };

    // Public
    return {
      defaultNumbersAdd: defaultNumbersAdd,
      getAnswer: getAnswer,
      modifynumbers: modifynumbers
    };
}());

// Then you can use the object as it already exists
myclass.method();

我想你被这个关键字弄糊涂了

此选项指当前对象上下文。 设置“ 间隔” 后, 您可以将函数传递到另一个背景中 < code> this 意味着别的东西。 所以您可以将 < code> this 指定给一个变量, 该变量传递给当前引用的对象, 或者在 < code> default Innumbers. add 中传递给 vars 属性 :

this.defaultNumbersAdd = function(){
   var ans = this.ans,
   n1 = this.n1,
   n2 = this.n2;

   this.hehe =setInterval(function(){
      //just an example of inert function...
      //the truth is i can t grab the this.n1 and this.n2...
      ans = n1 + n2;
   },100);
   clearTimeout(this.hehe);
};

我通常会为此宣布一个新的变数:

window.myclass = function(){
....
....

var self = this
....
....
}

现在你可以自称自己了......你想怎样就怎样

< 加强 > 点 # 1 < / 强 > : 如果您想要从对象中获取全部成员变量, 请使用 < code > (.. in.) :

// output all keys and values
for(key in myclassins) {
    console.log(key, myclassins[key]);
}

请注意, 函数在 JavaScript 中是头等变量, 所以如果您只想要列出 < code> myslegins 中的非功能成员变量, 请做 :

// output all keys and values that are not functions
for(key in myclassins) {
    if(!myclassins[key] instanceof Function) {
        console.log(key, myclassins[key]);
    }
}

point#2 :在 JavaScript 中, this 变量被称为函数的 context 。上下文可能会改变 -- -- 例如,当您调用 set Interval 时,它会导致匿名函数以 的上下文运行,而不是以当前对象的上下文运行。如果您想要引用当前对象的上下文,请在您构建器的起始处将它存储到另一个变量中,例如 var self= this; ,然后在匿名 set Interval 函数中,当您想要引用对象时,则引用 self

这是因为 JavaScript 支持 < em> closures , 这意味着当您定义函数时, 该新函数可以访问当前范围内存在的所有变量, 包括( 在此情况下) < code > self

<强 > 注 :





相关问题
selected text in iframe

How to get a selected text inside a iframe. I my page i m having a iframe which is editable true. So how can i get the selected text in that iframe.

How to fire event handlers on the link using javascript

I would like to click a link in my page using javascript. I would like to Fire event handlers on the link without navigating. How can this be done? This has to work both in firefox and Internet ...

How to Add script codes before the </body> tag ASP.NET

Heres the problem, In Masterpage, the google analytics code were pasted before the end of body tag. In ASPX page, I need to generate a script (google addItem tracker) using codebehind ClientScript ...

Clipboard access using Javascript - sans Flash?

Is there a reliable way to access the client machine s clipboard using Javascript? I continue to run into permissions issues when attempting to do this. How does Google Docs do this? Do they use ...

javascript debugging question

I have a large javascript which I didn t write but I need to use it and I m slowely going trough it trying to figure out what does it do and how, I m using alert to print out what it does but now I ...

Parsing date like twitter

I ve made a little forum and I want parse the date on newest posts like twitter, you know "posted 40 minutes ago ","posted 1 hour ago"... What s the best way ? Thanx.