1.使用Object或对象字面量创建对象
JS中最基本创建对象的方式:
var student = new Object(): student.name = 'xiaoming'; student.age = '20';
这样,一个student对象就创建完毕,拥有2个属性name以及age,分别赋值为'xiaoming'和20.
字面量方式创建对象:
var student = { name : 'xiaoming', age : 20 };
2.工厂模式创建对象
JS中没有类的概念,那么我们不妨就使用一种函数将以上对象创建过程封装起来以便于重复调用,同时可以给出特定接口来初始化对象
function createStudent(name,age){ var obj = new Object(); obj.name = name; obj.age = age; return obj; } var student1 = createStudent("dichou1",20) var student2 = createStudent("dichou2",20) var student3 = createStudent("dichou3",20)
3.构造函数模式创建对象
构造函数和普通函数的区别:
1.实际上并不存在创建构造函数的特殊语法,其与普通函数的唯一区别在于调用方法.对于任意函数,使用new操作符调用,那么他就是构造函数;不适用new操作符调用,那么他就是普通函数.
2.按照惯例,我们约定构造函数名以大写字母开头,普通函数以小写字母开头,这样有利于显性区分二者.例如new Array(),new Object().
3.使用new操作符调用构造函数时,会经历(1)创建一个新对象;(2)将构造函数作用域赋给新对象(使this指向该新对象);(3)执行构造函数代码;(4)返回新对象;4个阶段.
function Student(name, age) { this.name = name; this.age = age; this.alertName = function(){ alert(this.name) }; } function Fruit(name, color) { this.name = name; this.color = color; this.alertName = function(){ alert(this.name) }; }
再创建对象并用instanceof操作符检测对象类型进行区分
var v1 = new Student("easy", 20); var v2 = new Fruit("apple", "green"); alert(v1 instanceof Student); //true alert(v2 instanceof Student); //false alert(v1 instanceof Fruit); //false alert(v2 instanceof Fruit); //true alert(v1 instanceof Object); //true 任何对象均继承自Object alert(v2 instanceof Object); //true 任何对象均继承自Object
4.原型的模式创建对象
function Student() { this.name = 'easy'; this.age = 20; } Student.prototype.alertName = function(){ alert(this.name); }; var stu1 = new Student(); var stu2 = new Student(); stu1.alertName(); //easy stu2.alertName(); //easy alert(stu1.alertName == stu2.alertName); //true 二者共享同一函数