直接声明对象
1 2 3 4 5 6 7 8 9 10
| 1var dog = {
2 name: 'Benji',
3 talk:
4 function(){
5 alert('Woof, woof!');
6 }
7};
8alert(typeof(dog));
9dog.talk();
10 |
1 2
| 1 这样dog对象拥有那么属性和talk函数。
2 |
也可以用构造函数
1 2 3 4 5 6 7
| 1//--------构造函数--------
2function Hero() {
3 this.occupation = 'Ninja';//职业是武士
4}
5var hero = new Hero();//创建新对象
6alert(hero.occupation);//调用属性
7 |
1 2 3 4 5 6 7 8 9 10 11 12 13
| 1//---------带参的构造函数-----------
2function Hero(name) {
3 this.name = name;
4 this.occupation = 'Ninja'; //职业是武士
5 //行为
6 this.whoAreYou = function() {
7 return "I'm " + this.name + " and I'm a " + this.occupation;
8 }
9}
10 var h1 = new Hero('Michelangelo');
11 var h2 = new Hero('Donatello');
12 alert(h1.whoAreYou());
13 |