如何在原型函数中设置对象属性(范围问题)? [英] How to set object property in prototype function (scope problem)?

查看:51
本文介绍了如何在原型函数中设置对象属性(范围问题)?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是一件小事,我已经忘记了.可能有重复 - 我搜索了一点,找到了相似的,但找不到那么简洁.

This is something trivial, which I've forgotten. There are possibly duplicates - I searched a little, found similar, but couldn't find as concise.

   String.prototype.test = function(){this.bar = this.length + 2;}

   var str = "foo";
   str.test();

   console.log(str);                         // foo
   console.log(str.bar);                     // undefined

很确定这与 this 被困在闭包中有关.

Pretty sure it has to do with this being trapped in the closure.

推荐答案

在这种情况下与您创建字符串的方式有关.试试:

Has to do with the way you're creating your string in this case. Try:

var str = new String("Foo");

你会发现它神奇地工作.:-]

and you'll find it magically working. :-]

查看示例:http://jsbin.com/odozo3/edit

这篇关于如何在原型函数中设置对象属性(范围问题)?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆