这是我刚发布的问题的后续跟进.我想知道你在使用MyClass.prototype定义方法时如何处理javascript clases中的成员变量.
如果在构造函数中定义所有方法:
function MyClass(){
this.myMethod = function(){}
}
Run Code Online (Sandbox Code Playgroud)
您可以很好地声明成员变量并从方法中访问它们:
function MyClass(){
var myVar = "hello";
this.myMethod = function(){
alert(myVar);
}
}
Run Code Online (Sandbox Code Playgroud)
当使用Object.prototype技术时,你会失去这种精确性,并且必须这样做;
function MyClass(){}
MyClass.prototype.myVar = "hello";
MyClass.prototype.myMethod = function(){alert(this.hello)};
Run Code Online (Sandbox Code Playgroud)
每次访问成员变量时,我都不会疯狂地写"this".我想使用Object.prototype方法出于内存和灵活性的原因,但在语法方面看起来很笨拙.这是你们一般的工作方式吗?
谢谢,
-摩根
Tri*_*ych 19
您应该克服使用this指针访问成员变量的厌恶.
在构造函数中分配成员变量,您可以使用原型方法访问它们:
function Cat(){
this.legs = 4;
this.temperament = 'Apathetic';
this.sound = 'Meow';
}
Cat.prototype.speak = function(){alert(this.sound)}
var cat = new Cat();
cat.speak();
Run Code Online (Sandbox Code Playgroud)
是的,这些对象属性是公开的,但正如Guido所说,我们都是成年人.毕竟,Javascript是一种纯文本,松散类型的解释语言.在这种环境中"私人"变量的好处充其量是不稳定的.
我说只是明确而明确地说明你的对象应该如何被访问,并且违规者会自行承担风险.
meo*_*ouw 15
对象属性的可见性根据您声明它们的方式而有所不同
function Cat( name ) {
//private variable unique to each instance of Cat
var privateName = 'Cat_'+Math.floor( Math.random() * 100 );
//public variable unique to each instance of Cat
this.givenName = name;
//this method has access to private variables
this.sayPrivateName = function() {
alert( privateName );
}
}
//this variable is shared by all cats
Cat.prototype.generalName = 'tiddles';
//this method is shared by all cats and has no access to private vars
Cat.prototype.sayname = function( type ) {
alert( this[type+'Name'] || 'private!' );
}
var vic = new Cat('Victor');
var ellers = new Cat('Elmore');
vic.sayname('general'); //tiddles
vic.sayname('given'); //Victor
vic.sayname('private'); //private - no access
vic.sayPrivateName(); //cat will say its name
ellers.sayname('general'); //tiddles
ellers.sayname('given'); //Elmore
ellers.sayname('private'); //private - no access
ellers.sayPrivateName(); //cat will say its name
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
22943 次 |
| 最近记录: |