将函数添加为包含此值的属性

Adding functions as properties including a this value

本文关键字:属性 包含此 函数 添加      更新时间:2023-09-26

在向对象添加包含this的函数时遇到问题。它产生了我没有预料到的结果,这让我有些困惑。我试着用Object.create()重写代码,结果出现了一个错误。我肯定是忽略了一些简单的事情。如何确保qaz.execute隐式绑定到qaz?谢谢你的帮助。

// Version 1:
var qaz = {}; // [[Prototype]] will point to Object.prototype.
qaz.execute = function(){ console.log( "qaz: " + this ) };
qaz.execute(); // qaz: [object Object] (Why not qaz or even global/undefined?)
// Version 2:
var qaz = Object.create(null); // [[Prototype]] will be null.
qaz.execute = function(){ console.log( "qaz: " + this ) };
qaz.execute(); // TypeError: can't convert this to primitive type (Why?)
// Version 2:
var qaz = Object.create(null); // [[Prototype]] will be null.
qaz.execute = function(){ console.log( "qaz: " + this ) };
qaz.execute(); // TypeError: can't convert this to primitive type (Why?)

因为quz没有从Object.prototype继承toString。您可以执行以下操作:

var qaz = Object.create(null); // [[Prototype]] will be null.
qaz.execute = function(){ console.log( "qaz: " + 
Object.prototype.toString(this) ); };
qaz.execute();

或者正如我和埃尔克兰斯的评论中所说的那样;根本不将对象转换为字符串,并按原样记录对象(可能在IE中不起作用):

var qaz = Object.create(null); // [[Prototype]] will be null.
qaz.execute = function(){ console.log( "qaz: ", this); };
qaz.execute();

很难准确说出你想要实现的目标。我建议你看看这个https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/this#this_on_the_object's_prototype_chain

它应该能让你更好地掌握this

据我所知,如果你想记录qaz到底是什么,试试这个

var qaz = {}; 
qaz.execute = function(){ return this };
console.log("qaz: " + qaz.execute());

然而,它不会打印"qaz",但我认为,它会打印qaz的所有属性。如果你想了解更多关于将内容输出到控制台的信息,请阅读此处https://developer.mozilla.org/en-US/docs/Web/API/console#Outputting_text_to_the_console