我知道以前已经回答过了,但我仍然感到困惑(这不完全是我的错,因为我注意到答案可以根本不同).
我来自Java背景,所以如果你可以定义任何东西作为静态,私人,公共等等,那么应该帮助我理解.
基本上我想做一个完全自定义的类,但不确定原型/等等.
示例(使用一种功能类型):
function myClass() { var a; var b; var helper = function() { this.a += this.b; } var helper2 = function(a,b) { return(a + b); } var getA = function() { return(this.a); { var staticMethodThatNeedsToBePublic = function() {} } var myInstance = new myClass(); myClass.prototype.example1 = function(){}; myClass.example2 = function(){};
那么这实际上应该如何写? (我试图包含所有的基本功能类型,但是如果我错过了任何随意添加的话)[注意:我不是特别关心这个具体的例子,我只是认为这可能有助于对话,但随意只是回答我的一般问题]
解决方法
简单的回答你的问题:使用原型.始终使用原型.
主要区别在于,如果使用this.foo = function(){}附加函数,该函数将为该类的每个实例重新声明.使用func.prototype.foo = function(){}附加意味着该函数只能被声明一次,并且该属性在调用它应该引用的类的实例时被更改.
你的代码变成:
function myClass(){ // constructor } myClass.prototype = new superClass(); myClass.constructor = myClass; myClass.prototype = { helper : function(){},helper2 : function(){} }; var myInstance = new myClass();
如何添加方法的完整列表从大约5年前写的文章中的一个类的属性:
http://www.htmlgoodies.com/primers/jsp/article.php/3600451/Javascript-Basics-Part-8.htm
function Cat(name,color){ /* Constructor: any code in here is run when the object is created */ Cat.cats++; /* Private variables and functions - may only be accessed by private or privileged functions. Note that 'name' and 'color',passed into the Class,are already private variables. */ var age = 0; var legs = 4; function growOlder(){ age++; } /* Public variables - may be accessed publicly or privately */ this.weight = 1; this.length = 5; /* Privileged functions - may be accessed publicly or privately May access Private variables. Can NOT be changed,only replaced with public versions */ this.age = function(){ if(age==0) this.length+=20; growOlder(); this.weight++; } } /* Prototyped Functions - may be accessed publicly */ Cat.prototype = { talk: function(){ alert('Meow!'); },callOver: function(){ alert(this.name+' ignores you'); },pet: function(){ alert('Pet!'); } } /* Prototyped Variables - may be accessed publicly. May not be overridden,only replaced with a public version */ Cat.prototype.species = 'Cat'; /* Static variables and functions - may be accessed publicly */ Cat.cats = 0;