如果我们有
var randomname = {};
randomname.attribute = 'something';
function randomname(){
alert(randomname.attribute);
}
randomname();
javascript 会抛出任何错误吗?
这是为什么?
难道javascript不能通过你调用的方式就知道你追求的是什么吗?
最佳答案
它应该给你一个 TypeError异常 - 试图调用一个对象 - 在 Firebug 的控制台中观察到的行为是不正确的......
FunctionDeclaration是 hoisted到其封闭范围的顶部,您的代码实际上按以下顺序执行:
// FunctionDeclaration is hoisted
function randomname(){
alert(randomname.attribute);
}
// the var has no observable effect, because
// the randonmane identifier is already defined
randomname = {};
randomname.attribute = 'something';
randomname(); // TypeError, randomname is not callable.
进入执行上下文时,Variable Instantiation进程(在 ES5 中又名 Declaration Binding Instantiation)定义 Activation Object 上的属性(AO,这是一个不可访问的对象,它在局部范围内保存变量、函数声明和函数参数的标识符),顺序如下:
FormalParameterList标识符(对于 Function Code )FunctionDeclaration标识符VariableDeclaration标识符A VariableDeclaration不会覆盖已经在 AO 中定义的标识符(例如,通过前两个步骤之一),但赋值将在运行时完成。
例如:
(function (foo) {
var foo; // doesn't affect the existing `foo` identifier
return typeof foo;
function foo () {}
})('string'); // yields "function"
但如果进行了赋值,则标识符的值将被替换,例如:
(function (foo) {
var foo = {};
return typeof foo;
function foo () {}
})('string'); // yields "object"!!
在上面的示例中,调用函数时,-但在代码执行之前- foo标识符在激活对象(又名变量对象)上设置。
首先它被赋值给形参,值'string' , 然后都是 FunctionDeclaration函数体上的 被检查,一个名为 foo 的函数找到了,那么foo标识符将指向该函数。
之后,检查所有变量声明,我们有一个标识符为 foo , 但此时尊重它的值(value)——记住函数还没有被执行——。
此时,函数已准备好执行,其词法和变量环境已设置。
函数中首先要执行的是赋值 foo = {}; ,它取代了我们之前对函数的引用。
为什么它在其他浏览器和 Firefox 上的行为不同?
因为:
由于 Firebug 通过包装在 with 中来评估代码声明,这会导致 FunctionDeclaration在 statement context -a Mozilla's Function Statement- 中进行评估。
要显示 Function 语句在 Mozilla 实现上的行为,请考虑以下示例:
if (true) {
function foo () { return 'true!';}
} else {
function foo () { return 'false??!';}
}
foo();
在 Mozilla 中你会得到 'true!' ,而在其他实现中你会得到 'false??!' - 甚至在 IE 上。
那是因为函数定义是在运行时在语句上下文中(在 if 的真实分支中)进行的,而在其他实现中,函数声明是在解析时.
上面的例子实际上应该产生一个 SyntaxError任何实现上的异常,但它们中的任何一个都不会发生......
A FunctionDeclaration应该只允许在全局代码中或直接在函数的 FunctionBody 中使用。
A lot of people可以互换使用函数声明和函数语句这两个术语,但这是完全错误的,ECMAScript 没有定义函数语句,是一个 non-standard feature .
规范有一个简短的note关于这个问题:
NOTE: Several widely used implementations of ECMAScript are known to support the use of FunctionDeclaration as a Statement. However there are significant and irreconcilable variations among the implementations in the semantics applied to such FunctionDeclarations. Because of these irreconcilable difference, the use of a FunctionDeclaration as a Statement results in code that is not reliably portable among implementations. It is recommended that ECMAScript implementations either disallow this usage of FunctionDeclaration or issue a warning when such a usage is encountered. Future editions of ECMAScript may define alternative portable means for declaring functions in a Statement context.
尝试在全局执行上下文中运行您的代码 - 在一个简单的 <script> 中element- 你会看到它在 Firefox 上也会崩溃:
<script type="text/javascript">
var randomname = {};
randomname.attribute = 'something';
function randomname(){
alert(randomname.attribute);
}
randomname();
</script>
你可以找到上面的例子here , 请确保打开 Firebug 的控制台,您将看到与在其他浏览器上相同的错误。
关于javascript - 对象名称与函数名称相同?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3663775/
总的来说,我对ruby还比较陌生,我正在为我正在创建的对象编写一些rspec测试用例。许多测试用例都非常基础,我只是想确保正确填充和返回值。我想知道是否有办法使用循环结构来执行此操作。不必为我要测试的每个方法都设置一个assertEquals。例如:describeitem,"TestingtheItem"doit"willhaveanullvaluetostart"doitem=Item.new#HereIcoulddotheitem.name.shouldbe_nil#thenIcoulddoitem.category.shouldbe_nilendend但我想要一些方法来使用
在控制台中反复尝试之后,我想到了这种方法,可以按发生日期对类似activerecord的(Mongoid)对象进行分组。我不确定这是完成此任务的最佳方法,但它确实有效。有没有人有更好的建议,或者这是一个很好的方法?#eventsisanarrayofactiverecord-likeobjectsthatincludeatimeattributeevents.map{|event|#converteventsarrayintoanarrayofhasheswiththedayofthemonthandtheevent{:number=>event.time.day,:event=>ev
我有一个表单,其中有很多字段取自数组(而不是模型或对象)。我如何验证这些字段的存在?solve_problem_pathdo|f|%>... 最佳答案 创建一个简单的类来包装请求参数并使用ActiveModel::Validations。#definedsomewhere,atthesimplest:require'ostruct'classSolvetrue#youcouldevencheckthesolutionwithavalidatorvalidatedoerrors.add(:base,"WRONG!!!")unlesss
好的,所以我的目标是轻松地将一些数据保存到磁盘以备后用。您如何简单地写入然后读取一个对象?所以如果我有一个简单的类classCattr_accessor:a,:bdefinitialize(a,b)@a,@b=a,bendend所以如果我从中非常快地制作一个objobj=C.new("foo","bar")#justgaveitsomerandomvalues然后我可以把它变成一个kindaidstring=obj.to_s#whichreturns""我终于可以将此字符串打印到文件或其他内容中。我的问题是,我该如何再次将这个id变回一个对象?我知道我可以自己挑选信息并制作一个接受该信
我想在一个没有Sass引擎的类中使用Sass颜色函数。我已经在项目中使用了sassgem,所以我认为搭载会像以下一样简单:classRectangleincludeSass::Script::FunctionsdefcolorSass::Script::Color.new([0x82,0x39,0x06])enddefrender#hamlengineexecutedwithcontextofself#sothatwithintemlateicouldcall#%stop{offset:'0%',stop:{color:lighten(color)}}endend更新:参见上面的#re
如果您尝试在Ruby中的nil对象上调用方法,则会出现NoMethodError异常并显示消息:"undefinedmethod‘...’fornil:NilClass"然而,有一个tryRails中的方法,如果它被发送到一个nil对象,它只返回nil:require'rubygems'require'active_support/all'nil.try(:nonexisting_method)#noNoMethodErrorexceptionanymore那么try如何在内部工作以防止该异常? 最佳答案 像Ruby中的所有其他对象
我在Rails工作并有以下类(class):classPlayer当我运行时bundleexecrailsconsole然后尝试:a=Player.new("me",5.0,"UCLA")我回来了:=>#我不知道为什么Player对象不会在这里初始化。关于可能导致此问题的操作/解释的任何建议?谢谢,马里奥格 最佳答案 havenoideawhythePlayerobjectwouldn'tbeinitializedhere它没有初始化很简单,因为你还没有初始化它!您已经覆盖了ActiveRecord::Base初始化方法,但您没有调
我有一个这样的哈希数组:[{:foo=>2,:date=>Sat,01Sep2014},{:foo2=>2,:date=>Sat,02Sep2014},{:foo3=>3,:date=>Sat,01Sep2014},{:foo4=>4,:date=>Sat,03Sep2014},{:foo5=>5,:date=>Sat,02Sep2014}]如果:date相同,我想合并哈希值。我对上面数组的期望是:[{:foo=>2,:foo3=>3,:date=>Sat,01Sep2014},{:foo2=>2,:foo5=>5:date=>Sat,02Sep2014},{:foo4=>4,:dat
我有一个服务模型/表及其注册表。在表单中,我几乎拥有服务的所有字段,但我想在验证服务对象之前自动设置其中一些值。示例:--服务Controller#创建Action:defcreate@service=Service.new@service_form=ServiceFormObject.new(@service)@service_form.validate(params[:service_form_object])and@service_form.saverespond_with(@service_form,location:admin_services_path)end在验证@ser
我正在尝试用ruby中的gsub函数替换字符串中的某些单词,但有时效果很好,在某些情况下会出现此错误?这种格式有什么问题吗NoMethodError(undefinedmethod`gsub!'fornil:NilClass):模型.rbclassTest"replacethisID1",WAY=>"replacethisID2andID3",DELTA=>"replacethisID4"}end另一个模型.rbclassCheck 最佳答案 啊,我找到了!gsub!是一个非常奇怪的方法。首先,它替换了字符串,所以它实际上修改了