小编Iva*_*own的帖子

JavaScript 类和“this”

class Aa {
    methodA() {
        console.log('welcome to method a')
    }
    methodB() {
        console.log('welcome to method b')
        //   methodA() // Fails!! Uncaught ReferenceError: methodA is not defined
        this.methodA() // Works because of this.
    }
}

let myclass = new Aa()
myclass.methodB()
Run Code Online (Sandbox Code Playgroud)

简洁地解释为什么在调用您已经使用的类的另一个方法时需要使用“this”的最佳方法是什么?

直觉可能会说,好吧,如果 JS 知道我正在使用一个类的方法,那么它就知道那个类......因为我正在使用它的方法......那么为什么它不能找到另一个方法没有我告诉它的同一个类......是的'这个'同一个地方!

相比之下,函数可以毫无问题地做到这一点:

function a() {
    console.log('welcome to function a')
}
function b() {
    console.log('welcome to function b')
    a() // works without any sort of 'scope help'
}
b()
Run Code Online (Sandbox Code Playgroud)

我希望能够解释它,而不会让人们分心,需要知道它的最深层原因。如果可以的话,哈!

我的一部分只是想说,“这就是 JS 类的工作方式。你必须'这个' - 化事情。”

javascript

4
推荐指数
2
解决办法
1095
查看次数

过滤不包含来自其他数组的字符串的字符串?

我想通过排除包含黑名单数组中的任何子字符串的网址来过滤网址数组。

const urls = [
'http://example.com/people/chuck', 
'http://example.com/goats/sam', 
'http://example.com/goats/billy', 
'http://example.com/goats/linda', 
'http://example.com/cows/mary', 
'http://example.com/cows/betty', 
'http://example.com/people/betty']

const blacklist = ['cows', 'goats']

let cleanUrls = [];
Run Code Online (Sandbox Code Playgroud)

我可以用 for 循环来做到这一点,但我想找到一种使用过滤器和/或减少的干净/简洁的方法。

如果我不需要遍历 x 个黑名单项目:

cleanUrls = urls.filter( url => !url.includes(blacklist[0]) )                  
                .filter( url => !url.includes(blacklist[1]) ) 
Run Code Online (Sandbox Code Playgroud)

我也不想只用 forEach 或 map 遍历黑名单,因为如果特定 url 与任何黑名单条目匹配,我想立即停止。

请简单的JS。谢谢你。:)

javascript arrays string filtering

2
推荐指数
1
解决办法
1104
查看次数

标签 统计

javascript ×2

arrays ×1

filtering ×1

string ×1