gpt4 book ai didi

javascript mixin 访问对象 this

转载 作者:行者123 更新时间:2023-12-01 02:25:54 25 4
gpt4 key购买 nike

我创建了一个对象和一个 mixin,我已将 mixin 分配给该对象,但我似乎无权从 mixin 访问该对象?

mixin.js

module.exports = {
doSomething: () => {
let something = this.something.title;
}
};

对象.js

class Thing {   
constructor(something) {
this.something = something;
}

_otherFunction() {
// does stuff
}
}

module.exports = Thing;

index.js

const Something = require('./mixin');
const Thing = require('./Object');

Object.assign(Thing.prototype, Something);

当我实例化 Thing 并调用 doSomething() 时,它无法访问 this.something...所以

let thing = new Thing({title: 'abc'});
thing.doSomething();

我收到错误无法读取未定义的属性“标题”

最佳答案

您需要放弃箭头函数,转而使用普通函数,因为箭头函数失去了 this 的范围。

class Thing {   
constructor(something) {
this.something = something;
}
}

const mixin = {
// changed arrow function to regular function
doSomething: function () {
console.log(this.something.title)
}
}

const thing = new Thing({title: 'abc'})
Object.assign(thing, mixin)
thing.doSomething()

来自MDN: Arrow Functions :

An arrow function expression... and does not have its own this, arguments, super, or new.target.

许多人错误地认为箭头函数的唯一特征是语法较短 - 事实并非如此。它的主要实用功能是它不会创建自己的 this

关于javascript mixin 访问对象 this,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48806723/

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