简体   繁体   English

类中的对象方法

[英]Object Methods within a Class

I'm new to using the ES6 classes , I'm trying to figure out how to group methods within a class I'm creating for a Table so methods such as sort, resize, etc... 我是使用ES6 classes新手,我试图弄清楚如何在为Table创建的类中对方法进行分组,以便进行排序,调整大小等方法。

class Table extends someClass{
    myMethods(){
        //BLAH      
    }
    var column={
        sort:()=>{
            console.log('firing');
        },
        resize:{
            mousedown:()=>{

            },
            mousemove:()=>{

            },
            mouseup:()=>{

            },
            mouseout:()=>{

            }
        }       
    },
    var cells={
        edit:()=>{
            console.log('firing');
        }
    }
}

//ERROR (Unexpected Identifier) //错误(意外标识符)

The problem is the Table class is already extending the (default base class) someClass and I would say extends Column class or something but I can't since it already is extending the base class. 问题是Table类已经扩展了(默认基类) someClass ,我想说扩展了Column类之类,但是我不能,因为它已经在扩展基类。

Question: How can I organize my methods sort , resize inside a Class which already extends another class? 问题:如何在一个已经扩展了另一个类的类中组织我的方法sortresize (or is this non-standard, and if so please provide the proper way.) (或者这是非标准的,如果是,请提供正确的方法。)

Your code doesn't work because you are using the var keyword in the class body. 您的代码无效,因为您在类主体中使用了var关键字。 You can only have methods in a class body. 您只能在类主体中具有方法。 You can create properties for a class by setting values to them in the methods. 您可以通过在方法中为其设置值来为类创建属性。 For example: 例如:

class Table extends someClass {
    constructor() {
        this.column = {
            sort: () => {
                console.log('firing');
            },
            resize: () => {
                console.log('firing');
            }
        };

        this.cells = {
            edit: () => { 
                console.log('firing');
            }
        }

    }

    myMethods() {
        //BLAH      
    }
}

Now you can access methods like so: 现在您可以访问如下方法:

var table = new Table();
table.column.sort();

This class Table syntax declares a class with type Table . class Table语法声明一个类型为Table的类。 The {} syntax, for example: {}语法,例如:

{
    edit: () => { 
        console.log('firing');
    }
}

creates objects without a type. 创建没有类型的对象。

Here's a guide on ES6 classes which should answer your other questions. 这是有关ES6类的指南,应回答您的其他问题。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM