object-literal

Adding Prototype to JavaScript Object Literal

只愿长相守 提交于 2019-11-26 04:39:09
问题 STORE = { item : function() { } }; STORE.item.prototype.add = function() { alert(\'test 123\'); }; STORE.item.add(); I have been trying to figure out what\'s wrong with this quite a while. Why doesn\'t this work? However, it works when I use the follow: STORE.item.prototype.add(); 回答1: The prototype object is meant to be used on constructor functions, basically functions that will be called using the new operator to create new object instances. Functions in JavaScript are first-class objects,

Template String As Object Property Name

天大地大妈咪最大 提交于 2019-11-26 04:24:28
问题 Why does JavaScript not allow a template string as an object property key? For example, when I input: foo = {`bar`: \'baz\'} into the NodeJS REPL, it throws a SyntaxError with \"Unexpected template string\" with a long stack trace. Property values are fine, however, which is not as unexpected. Similar errors happen in the browser, for example, Firebug throws a SyntaxError with \"invalid property id\". Template strings are allowed in \"computed property names\". For instance, this compiles

Adding/removing items from a JavaScript object with jQuery

十年热恋 提交于 2019-11-26 02:16:12
问题 I have a JavaScript object as follows: var data = {items: [ {id: \"1\", name: \"Snatch\", type: \"crime\"}, {id: \"2\", name: \"Witches of Eastwick\", type: \"comedy\"}, {id: \"3\", name: \"X-Men\", type: \"action\"}, {id: \"4\", name: \"Ordinary People\", type: \"drama\"}, {id: \"5\", name: \"Billy Elliot\", type: \"drama\"}, {id: \"6\", name: \"Toy Story\", type: \"children\"} ]}; If I wanted to add/remove items to this list, how would I go about it using jQuery? The client wants this list

How can I add a key/value pair to a JavaScript object?

烈酒焚心 提交于 2019-11-26 01:18:10
问题 Here is my object literal: var obj = {key1: value1, key2: value2}; How can I add {key3: value3} to the object? 回答1: There are two ways to add new properties to an object: var obj = { key1: value1, key2: value2 }; Using dot notation: obj.key3 = "value3"; Using square bracket notation: obj["key3"] = "value3"; The first form is used when you know the name of the property. The second form is used when the name of the property is dynamically determined. Like in this example: var getProperty =

How to use a variable for a key in a JavaScript object literal?

喜夏-厌秋 提交于 2019-11-25 22:10:34
问题 Why does the following work? <something>.stop().animate( { \'top\' : 10 }, 10 ); Whereas this doesn\'t work: var thetop = \'top\'; <something>.stop().animate( { thetop : 10 }, 10 ); To make it even clearer: At the moment I\'m not able to pass a CSS property to the animate function as a variable. 回答1: { thetop : 10 } is a valid object literal. The code will create an object with a property named thetop that has a value of 10. Both the following are the same: obj = { thetop : 10 }; obj = {