将函数添加为包含此值的属性
Adding functions as properties including a this value
在向对象添加包含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
相关文章:
- 带有填充属性的SVG矩形显示在包含元素的上方插入框阴影
- 在循环中包含特定属性
- 我发现了一些只在移动设备上可见的垃圾邮件链接,我可以'找不到包含此垃圾邮件链接的脚本的位置
- 如果el包含此文本,请从中删除此字符串
- Javascript函数'的属性,该属性包含其代码
- CssClass 属性的此值是什么意思
- Blogger不会保存包含此JavaScript的模板
- jQuery 选择
,自定义属性包含“:” - 属性包含选择器 * 替代
- 获取其子属性包含值的对象
- 如何使用jQuery'检查连字符后的内容;s”;属性包含前缀选择器”;
- 将函数添加为包含此值的属性
- 将文本替换为包含此文本的文本框
- 为什么我得到“;未捕获的类型错误:无法读取属性“”;此变量出错
- 使用regex查看字符串是否仅包含此单词,而不包含在另一个单词中
- Regex匹配包含此顺序的字母的整个单词(空格之间的字符)
- 属性包含返回空数组的单词选择器
- 我怎样才能得到每一个"标签which "href"属性包含单词"youtube&
- 击倒“;如果viewModel属性包含'一些文本'&”;
- 属性包含使用change的选择器[name*= " value "]