gpt4 book ai didi

javascript - 如何从 JavaScript 中的不同对象借用方法?

转载 作者:行者123 更新时间:2023-11-30 05:32:57 24 4
gpt4 key购买 nike

我是继承的新手,我只是想从 JavaScript 中的不同对象继承一个方法,但是当我运行代码时,它给出了一个未定义的函数错误。

谁能帮我如何从不同的对象继承方法?

下面是 JS 片段:

var palestrina = {
work: "MTS",
describe: function() {
return this.work;
}
};

var pale = {
work: "STMS"
describe: palestrina.describe.bind(this)
};

console.log(palestrina.describe());
console.log(pale.describe());

JSfiddle for the same

最佳答案

this 的值由当前函数的调用方式决定。

因为您不在函数中,所以它将是 window

在创建对象之前,无法获取可传递给 bind 的对 pale 的引用。

但是,您不需要这样做。由于 this 的值取决于函数的调用方式(而不是它的构造方式),您可以只复制对函数的引用:

var pale = {
work: "STMS",
describe: palestrina.describe
};

关于javascript - 如何从 JavaScript 中的不同对象借用方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25744507/

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