aralejs / class

Class Utility
aralejs.org/class
102 stars 88 forks source link

用class实现OOP时,在方法中使用属性,是不是总是得用上this前缀? #2

Closed idevsoft closed 11 years ago

idevsoft commented 11 years ago

class对于一个Java开发人员觉得非常亲切。 一个疑问是:在方法中使用属性,是不是总是得用上this前缀?方法内的缺省变量都属于局部变量,没带this前缀的同名变量误以为是类属性,容易导致错误。

define(function(require, exports, module) {
    var Class = require('class');
    var MyObj = Class.create({
        initialize : function(_x, _y) {
            this.x = _x;
            this.y = _y;
        },
        z : 1,
        test : function(which) {
            if (this.x == 1 && this.y == 2) {
                  this.z = 3;
            }
            else {
                  this.z = 4;
            }
        }
    });
    module.exports = MyObj;
});

问题是如果每个对类变量的调用都带this前缀很麻烦,而且可能由于忘带this而出错。

是这样的吗?

popomore commented 11 years ago

恩,this 是指向实例的,比如你上面的代码

var obj = new MyObj();

obj 就是代码里面的 this。如果没有用 this 并且未声明,那么这个 x 是指向 window。

如果清楚知道 this 的指向,一般不会用错。

lifesinger commented 11 years ago

对,this 是必须的。不如去掉 this,会带来很多隐患,并且与传统编程习惯不一致。