JavaScript   发布时间:2022-04-16  发布网站:大佬教程  code.js-code.com
大佬教程收集整理的这篇文章主要介绍了Javascript“类”原型vs内部函数声明vs等大佬教程大佬觉得挺不错的,现在分享给大家,也给大家做个参考。
我知道以前已经回答过了,但我仍然感到困惑(这不完全是我的错,因为我注意到答案可以根本不同).

我来自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;

大佬总结

以上是大佬教程为你收集整理的Javascript“类”原型vs内部函数声明vs等全部内容,希望文章能够帮你解决Javascript“类”原型vs内部函数声明vs等所遇到的程序开发问题。

如果觉得大佬教程网站内容还不错,欢迎将大佬教程推荐给程序员好友。

本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。