Javascript 原型应该只用于类中的公共方法吗?
我有一个没有公共方法的js类。我在构造函数中使用var来创建这些方法,并使用methodName()调用它们。我是否应该改为使用class.prototype.methodName,并在类中使用此.methodName()调用它们?这两种方法的优点是什么?我知道原型方法会被复制到新实例中,因此速度更快。但是它们应该只用于类的API吗?JavaScript没有私有变量,因此使用模拟它们的模式会导致一些开销(运行代码需要更多的cpu和内存)。带有私人密码的代码可能更难维护 模拟私有成员的模式可以分为两种不同类型:Javascript 原型应该只用于类中的公共方法吗?,javascript,jquery,oop,prototype,Javascript,Jquery,Oop,Prototype,我有一个没有公共方法的js类。我在构造函数中使用var来创建这些方法,并使用methodName()调用它们。我是否应该改为使用class.prototype.methodName,并在类中使用此.methodName()调用它们?这两种方法的优点是什么?我知道原型方法会被复制到新实例中,因此速度更快。但是它们应该只用于类的API吗?JavaScript没有私有变量,因此使用模拟它们的模式会导致一些开销(运行代码需要更多的cpu和内存)。带有私人密码的代码可能更难维护 模拟私有成员的模式可以分为
//constructor for Person
var Person = function(){//<=start body of constructor function
//to properly use prototype and not cause your code to consume
// more resources to simulate something that isn't supported
// in JavaScript "private" variable names usually start with _
// so other programmers know not to set, get or call this directly
this._normalPrivate;
var religion = undefined;//<=instance specific private
this.religion = function(){//<=privileged function
console.log(religion);//<=can access private instance here
}
};
Person.prototype=(function(){//<=start body of function returning object for prototype
//All person instances share this, it's not instance specific
var doSomethingDangerous=function(){//<=private prototype
// doing something dangerous, don't want this to be called directly
};
return {
doSomething:function(){//<=priviliged method, can access private prototype
//we cannot access religion because it's defined in a different
// function body
//make sure we can do something dangerous
doSomethingDangerous();
}
};
}());
Person.prototype.constructor=Person;
Person.prototype.anotherMethod=function(){
//not a privileged method, cannot access doSomethingDangerous or religion
};
var ben = new Person();
要向其他程序员(以及未来的自己)表明doSomethingDangerous是私有的,您可以在其前面添加下划线:
Person.prototype._doSomethingDangerous=function(){...
更多关于原型、继承、混合的信息,请参见此处如果每个对象上的某些内容相同,则会放入原型中,不同的内容应归自己所有。如果它根本没有公共成员,那么创建这种类型的实例(ses)有什么意义?
Person.prototype._doSomethingDangerous=function(){...