javascript - es6中的[]()是怎样的用法
PHPz
PHPz 2017-04-11 12:20:29
[JavaScript讨论组]

看别人的代码时候,无意间看到[](){}这样的用法,但阅尽百度都没看到这个方法的详解,所以想咨询一下大家。
具体是在vuex里的store.js看到

[changeListStatus](state,bool){ state.isAllList = bool; }

const mutations = {  
    [changeListStatus](state,bool){  
        state.isAllList = bool;  
    },  
    [addNote](state) {  
        const newNote = {  
            text: 'New note',  
            favorite: !state.isAllList,  
            _rm: Math.random(),  
        }  
        state.notes.push(newNote);  
        state.activeNote = newNote;  
    },  
    [editNote](state, text) {  
        state.activeNote.text = text;  
    },  
    [deleteNote](state){  
        let rm = state.activeNote['_rm'];  
        let index = state.notes.findIndex(function(v,i){  
            if( rm == v['_rm'] ) return true;  
            return false;  
        });  
        if(index >= 0) state.notes.splice(index, 1);  
        state.activeNote = state.notes[0] || {};  
    },  
    [toggleFavorite](state){  
        state.activeNote['favorite'] = !state.activeNote['favorite']  
    },  
    [setActiveNote](state,note){  
        state.activeNote = note;  
    },  
}  
PHPz
PHPz

学习是最好的投资!

全部回复(2)
怪我咯

问题分解

var changeListStatus='foo';
var obj={
    [changeListStatus](state,bool){ state.isAllList = bool; }
}

=>

var changeListStatus='foo';
var obj={
    [changeListStatus]:function(state,bool){ state.isAllList = bool; }
}

=>

var obj={
    foo:function(state,bool){ state.isAllList = bool; }
}

[]表示属性内是可计算的,常见的是比如 给对象安装迭代器

var obj={}
obj[Symbol.iterator]=function(){}
黄舟

Computed Property Names
Method Properties
这两个语法一起用就是这样了

const methodName = "aaa";

const v = {
    [methodName](bar) {
        console.log("bar=", bar);
    }
};

v.aaa("BBBar"); // bar = BBBar
热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板
关于我们 免责申明 举报中心 意见反馈 讲师合作 广告合作 最新更新
php中文网:公益在线php培训,帮助PHP学习者快速成长!
关注服务号 技术交流群
PHP中文网订阅号
每天精选资源文章推送

Copyright 2014-2026 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号