gpt4 book ai didi

javascript - 视觉 : this in different scope get same object

转载 作者:行者123 更新时间:2023-11-30 14:03:41 25 4
gpt4 key购买 nike

我是 Vue 新手。我看到了这样一个演示:

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<div id="app">
{{fullname}}
</div>
<script src="https://cdn.jsdelivr.net/npm/vue@2.5.16/dist/vue.js"></script>
<script>
var app = new Vue({
el:'#app',
data:{
firstName: 'first',
lastName: 'last'
},
computed: {
fullname: {
get: function(){
console.log('getter');
return this.firstName + this.lastName;
},
set: function (newValue) {
console.log('setter:' + newValue);
let names = newValue.split(' ')
this.firstName = names[0]
this.lastName = names[names.length - 1]
}
}
}
})

</script>
</body>
</html>

如代码所示,有两个子函数get和set。在我看来,这两个函数中的 this 变量不应该相同(因为它们属于不同的范围)。但效果很好。有什么想法吗?

最佳答案

你有一个很大的误会。 this 与范围无关。它与绑定(bind)有关。

什么是范围

我们先不用CS语言,用普通话聊一会。范围决定了一个变量是否可以被访问。也就是说,它决定了一个变量的“全局性”和“局部性”。

例如:

let x = 0;

function foo () {
let y = 0;
}

x 在全局范围和 foo() 内部都在范围内。另一方面,y 仅在 foo() 范围内,在其外部无法访问。

什么是绑定(bind)

绑定(bind)与范围无关(从程序员的 Angular 来看)*。绑定(bind)确定属性属于哪个对象。

例如:

foo = {
a: function () {},
b: 0
}

bar = Object.create(foo); // create new instance of object foo

foo.a(); // here the function a() is bound to foo
bar.a(); // here the function a() is NOT bound to foo

let x = bar.b; // here we are NOT accessing foo.b!

this 是一种引用对象自身绑定(bind)的机制。当从属于的方法中调用时,它允许您编写 this.a() 而不是 foo.a()bar.a()到同一个对象。

所以当然是一样的。它们都绑定(bind)到同一个对象:fullname

* note: I say form the programmer's point of view because the javascript spec, which is written from a compiler writer's point of view, merges both concepts of scope and binding into something called context (and sometimes called "scope", so yes, in the spec "scope" sometimes does not mean scope, it means binding instead)

关于javascript - 视觉 : this in different scope get same object,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55860312/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com