总结js创建object的方式(对象)

2017-01-22  本文已影响13人  afb399d1a25f

https://my.oschina.net/u/941788/blog/110818

1、使用new操作符后跟Object构造函数 如:

var person = new Object(); 可以写成 var person = {};

person.name = "kitty";

person.age = 25;

2、使用“对象字面量”表示法,如:

var person = {

  name : "kitty",

  age:25

};

3、工厂模式 方法:

var createPerson = function(name,age,job){
var person = new Object();
person.name = name;
person.age = age;
person.job = job;
person.sayName = function(){
alert(person.name);
}
return person;
}

var person1 = createPerson("zh","62","Doctor");
person1.sayName();

4、构造函数模式 方法

function Person(name,age,job){
this.name = name;
this.age = age;
this.job = job;
this.sayName = function(){
alert(this.name);
};
};

var person1 = new Person("zhou",23,"test");
person1.sayName();

上一篇下一篇

猜你喜欢

热点阅读