简体   繁体   中英

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...

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.

Question: How can I organize my methods sort , resize inside a Class which already extends another class? (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. 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 . 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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