JS Object creating

上一篇 / 下一篇  2015-08-04 12:51:07 / 个人分类:JavaScript

Great work! You just created your very first object.

There are two ways to create an object: usingobject literal notation (which is what you just did) and using the object constructor.

Literal notation is just creating an object with curly braces, like this:

varmyObj = {
    type:'fancy',
    disposition:'sunny'};varemptyObj = {};

When you use the constructor, the syntax looks like this:

varmyObj =newObject();

This tells JavaScript. "I want you to make me anew thing, and I want that thing to be anObject.

You can add keys to your object after you've created it in two ways:

myObj["name"] ="Charlie";myObj.name="Charlie";

Both are correct, and the second is shorthand for the first. See how this is sort of similar to arrays?


TAG: Creating Object object creating

wilber.shinobi的个人空间 引用 删除 wilber.shinobi   /   2015-08-04 14:39:51
JS function with one parameter
var list = function (myArray) {
    for ( var key in myArray ){
        console.log(key);
    }
}
wilber.shinobi的个人空间 引用 删除 wilber.shinobi   /   2015-08-04 13:46:44
//  the object constructor
var friends = new Object();
friends.bill = new Object();
friends.steve = new Object();
friends.bill.firstName = "Bill";
friends.bill.lastName = "Gates";
friends.bill.number = "(86) 7777-7777";
friends.steve.firstName = "Steve";
friends.steve.lastName = "Jobs";
friends.steve.number = "(86) 8888-7777";

// either object literal notation
var friends2 = {
    bill: {
        firstName: "Bill",
        lastName: "Gates",
        number: "(86) 7777-7777"
    },
    steve: {
        firstName:"Steve",
        lastName: "Jobs",
        number: "(86) 8888-7777"
    }
};
wilber.shinobi的个人空间 引用 删除 wilber.shinobi   /   2015-08-04 13:07:40
var myOwnObject = new Object();
myOwnObject.name = "hello";
var myOwnObject2 = {
    hobbies:['basketball','jogging'],
    name:'xxxx',
    age:190
}
wilber.shinobi的个人空间 引用 删除 wilber.shinobi   /   2015-08-04 13:05:10
var myObject = {
  name: 'Eduardo',
  type: 'Most excellent',
  // Add your code here!
  interests:['Jogging','sleeping'] // array
  
};
wilber.shinobi的个人空间 引用 删除 wilber.shinobi   /   2015-08-04 13:00:51
Heterogeneous arrays sample with Object sample:
var myArray = [22,true,"Shang",new Object()];
wilber.shinobi的个人空间 引用 删除 wilber.shinobi   /   2015-08-04 12:56:17
var object1 = new Object();
var object2 = new Object();
var object3 = new Object();
object1.name = "object1's name";
object2["hometown"] = "SH";
object3.day = "Tuesday";

var object4 = {
    type:'fancy',
    disposition:'sunny'
}
var emptyObj = {};
 

评分:0

我来说两句

Open Toolbar