这是我刚刚发布的问题的跟进。
我想知道当使用MyClass.prototype定义方法时,大家如何处理javascript句中的成员变量。

如果在构造函数中定义所有方法:

function MyClass(){
 this.myMethod = function(){}
}

您可以很好地声明成员变量并从您的方法内部访问它们:
function MyClass(){
 var myVar = "hello";
 this.myMethod = function(){
  alert(myVar);
 }
}

当使用Object.prototype技术时,您会失去这种美感,而必须这样做。
function MyClass(){}
MyClass.prototype.myVar = "hello";
MyClass.prototype.myMethod = function(){alert(this.hello)};

每次访问成员变量时,我都不必写“this”,这一点我并不为之疯狂。出于内存和灵活性的原因,我想使用Object.prototype方法,但是在语法上似乎更加笨拙。这是你们一般的工作方式吗?

谢谢,

-摩根

最佳答案

您应该避免使用this指针访问成员变量。

在构造函数中分配成员变量,然后可以使用原型(prototype)方法访问它们:

function Cat(){
    this.legs = 4;
    this.temperament = 'Apathetic';
    this.sound = 'Meow';
}

Cat.prototype.speak = function(){alert(this.sound)}

var cat = new Cat();
cat.speak();

是的,那些对象属性是公共(public)的,但正如Guido所说,我们都是成年人。毕竟,JavaScript是纯文本,松散类型的解释语言。在这种环境下,“私有(private)”变量的好处充其量是不稳定的。

我说的是关于如何访问对象的明确明了的行为,违者将自担风险。

关于javascript - 面向对象的javascript中成员变量的最佳方法?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/436234/

10-09 16:51
查看更多