相关疑难解决方法(0)

如何创建一个JavaScript"类",将方法添加到原型并正确使用"this"

我总是被告知在JavaScript中模拟类的正确方法是在函数外添加方法,这将是你的类,如下所示:

function myClass()
{
    this.myProp = "foo";
}

myClass.prototype.myMethod = function()
{
    console.log(this);
}

myObj = new myClass();
myObj.myMethod();
Run Code Online (Sandbox Code Playgroud)

我一直在遇到this我的方法解析为全局Window对象的问题,最好在quirksmode上解释.

我已经尝试过做var that = this;Koch提到的技巧,但由于我的方法不在我的课堂上,我的that变量不再在范围内了.也许我只是不完全理解它.

有没有办法可以在JavaScript中创建一个类,其中每个实现都不重新创建方法,并且this总是指向对象?

编辑:

上面的简化代码可以工作,但我已经多次在上面声明一个与上面完全相同的"类",当我调用时myObj.myMethod(),它作为一个Window对象返回.我已经阅读了this我能找到的每一个解释,例如我链接到的那个,但仍然不明白为什么这个问题有时会发生.是否可以像上面this那样编写代码的情况Window

这是我目前遇到问题的实现,但当我将其简化为几行时,我不再有问题:

HTML文件:

<script type="text/javascript" src="./scripts/class.Database.js"></script>
<script type="text/javascript" src="./scripts/class.ServerFunctionWrapper.js"></script>
<script type="text/javascript" src="./scripts/class.DataUnifier.js"></script>
<script type="text/javascript" src="./scripts/main.js"></script>
Run Code Online (Sandbox Code Playgroud)

class.DataUnifier.js:

function DataUnifier()
{
    this._local = new Database();
    this._server = new ServerFunctionWrapper();
    this.autoUpdateIntervalObj = null;
}

DataUnifier.prototype.getUpdates = function() …
Run Code Online (Sandbox Code Playgroud)

javascript methods prototype this

7
推荐指数
1
解决办法
9481
查看次数

为什么这个闭包范围的变量会失去它的价值?

我在这里看到了这个Javascript测验:http://www.netfxharmonics.com/2008/01/NetFX-Harmonics-JavaScript-Quiz

我无法弄清楚这个问题:

(function(){
    var a = 1;
    var b = 2;

    (function( ) { a = b; var b; })( );

    console.log('a:'+ a);  // => "a:undefined"
    console.log('b:'+ b);  // => "b:2"
})()
Run Code Online (Sandbox Code Playgroud)

但是,如果var b;从内部函数中删除声明,那么a == 2正如您所期望的那样.

为什么会这样?

(你可以在这里玩它:http://jsfiddle.net/gnhMZ/)

javascript closures

6
推荐指数
1
解决办法
1905
查看次数

标签 统计

javascript ×2

closures ×1

methods ×1

prototype ×1

this ×1