我试图理解为什么我们在函数内部执行this.xyz?
比如考虑使用foo()
这个函数
function foo() {
this.value = "Shivom"
console.log(this.value) //Shivom
console.log(value) //Shivom
}
对此可以替代
function foo() {
value = "shivom"
console.log(this.value) //shivom
console.log(value) //shivom
}
同样,当In In使用websocket时,有人让我这么做
class cryptoTicker extends Component {
componentDidMount() {
this.socket = openSocket('https://coincap.io');
let updateCoinData = [...this.props.cryptoLoaded];
this.socket.on('trades', (tradeMsg) => {
componentWillUnmount() {
this.socket.disconnect();
}
而不是做这样的事情
var socket;
class cryptoTicker extends Component {
componentDidMount() {
socket = openSocket('https://coincap.io');
let updateCoinData = [...this.props.cryptoLoaded];
socket.on('trades', (tradeMsg) => {
componentWillUnmount() {
socket.disconnect();
}
[问题:]那么我们何时以及为什么在函数中使用this.xyz?如果有人能用上面给出的两个例子解释我吗?
好吧,简而言之:
var foo;
function bar(baz) {
foo = baz;
console.log(foo);
}
这样你的程序中只能有一个foo
值。这是一个单身/全球价值。
class Foo {
constructor() {
this.foo = undefined;
}
bar(baz) {
this.foo = baz;
console.log(this.foo);
}
}
let a = new Foo;
let b = new Foo;
a.bar(42);
b.bar('fortytwo');
在单个对象(this
)上使用类和对象以及设置属性允许您拥有对象/值的多个独立实例。这是OOP的基础。