简体   繁体   English

ES6 Javascript类和函数范围

[英]ES6 Javascript Class and function scopes

I am writing a simple js tab in new ES6 code but i am a bit troubles with scope of variables and exporting class. 我正在用新的ES6代码编写一个简单的js选项卡,但是在变量范围和导出类方面有点麻烦。

Here is my code 这是我的代码

import $ from 'jquery';
import '../css/_style.scss';
import './mediaupload.js';
//
let i, tabcontent, tablinks;
tabcontent = document.getElementsByClassName("tabcontent");
tablinks = document.getElementsByClassName("tablinks");
class SMDVadmin{
    openTab(evt, tabname){
        for (i = 0; i < tabcontent.length; i++) {
            tabcontent[i].style.display = "none";
        }
        for (i = 0; i < tablinks.length; i++) {
            tablinks[i].className = tablinks[i].className.replace(" active", "");
        }
        document.getElementById(tabname).style.display = "block";
        evt.currentTarget.className += " active";
    }
}
export default SMDVadmin;

and i am using the function openTab as 我正在使用功能openTab作为

<ul>
   <li><a href="#" onClick="openTab(e, tab1)" id="th1">HOme</a></li>
   <li><a href="#" onClick="openTab(e, tab2)" id="th2">Address</a></li>
</ul>

But on clicking there is an error Uncaught ReferenceError: openTab is not defined 但是单击时出现错误Uncaught ReferenceError: openTab is not defined

BUT, if i code like this,its working :) : 但是,如果我这样编码,它的工作:):

let i, tabcontent, tablinks;
tabcontent = document.getElementsByClassName("tabcontent");
tablinks = document.getElementsByClassName("tablinks");

const openTab = (evt, tabname) => {
    for (i = 0; i < tabcontent.length; i++) {
        tabcontent[i].style.display = "none";
    }
    for (i = 0; i < tablinks.length; i++) {
        tablinks[i].className = tablinks[i].className.replace(" active", "");
    }
    document.getElementById(tabname).style.display = "block";
    evt.currentTarget.className += " active";
}

window.openTab = openTab;

But i have more other functions and I want them to keep in a class to maintain a integrity 但我还有其他功能,我希望它们保留在一个类中以保持完整性

You've effectively "namespaced" your openTab method by putting it in a class. 您已经通过将openTab方法放在一个类中来有效地对其进行“命名空间”。 You must create an instance of the class and then call the method on that instance. 您必须创建该类的实例,然后在该实例上调用该方法。

var smdvAdmin = new SMDVadmin()

smdvAdmin.openTab()

Alternatively, you could make the method a static, thus not requiring a new instance: 另外,您可以将方法设为静态,因此不需要新的实例:

class SMDVadmin{
    static openTab(evt, tabname){}
}

SMDVadmin.openTab()

You may not need the class at all if you are importing a single method from a file. 如果要从文件导入单个方法,则可能根本不需要该类。

You could instead just export the method 您可以改为导出方法

const openTab = (evt, tabname) => {}

export default openTab;

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

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