微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

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;

原文地址:https://www.jb51.cc/js/153242.html

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐