JavaScript-引用其字段的对象函数 [英] JavaScript - object's functions referencing its fields

查看:50
本文介绍了JavaScript-引用其字段的对象函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是我的代码的(非常)简化版本:

Here is a (very) simplified version of my code:

    function Ctor() {
        this.i = 0;

        this.increment = function() { this.i++; },
        this.decrement = function() { this.i--; },

        this.display = function() { alert(this.i); }
    };

问题是,在运行代码时,在某些情况下this现在指向其他内容.我或多或少地了解到this将上下文从一个函数更改为另一个函数,但是尽管我的增量函数(和其他函数)可以借助闭包的神奇之处,记住"这应该是什么.

The problem is, when the code is run, under some circumstances this now points to something else. I do more or less understand that this changes context from one function to another, but I though my increment function (and the others) would, by the magic of closures, "remember" what this is supposed to be.

我试图完全消除这种情况,只在函数中引用i.那也失败了.

I tried just eliminating this altogether, and simply referencing i in the functions. That failed also.

这些功能应该是什么样的?

What should these functions look like?

推荐答案

您不能依赖JavaScript this中的内容. 有关此内容的更多信息主题.

You can not rely on what's in this in JavaScript. More on this topic.

我看到您可能想引入私有属性,例如OOP语言.约翰·雷西格(John Resig)很好地描述了这个问题.

I see you probably want to introduce private attributes like in OOP languages. John Resig described this issue very well.

function Field(val){
    var value = val;

    this.getValue = function(){
        return value;
    };

    this.setValue = function(val){
        value = val;
    };
}

var field = new Field("test");
field.value
// => undefined
field.setValue("test2")
field.getValue()
// => "test2" 

JavaScript的工作方式与Java,C ++或PHP等传统语言大不相同.但是你可以习惯了:)

JavaScript works a lot differently than conventional languages like Java, C++ or PHP. But you can get used to it :)

这篇关于JavaScript-引用其字段的对象函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆