Home > Web Front-end > JS Tutorial > body text

简单分析javascript面向对象与原型_jquery

WBOY
Release: 2016-05-16 15:57:57
Original
1086 people have browsed it

本文主要内容参考来自JavaScript高级程序设计,面向对象与原型章节:

1、工厂模式

ECMAScript 可以通过工厂模式来创建对象:

//工厂模式
function createObject(name, age) {
  var obj = new Object();                  //创建对象
  obj.name = name;                      //添加属性
  obj.age = age;
  obj.run = function () {                    //添加方法
    return this.name + this.age + '运行中...';
  };
  return obj;                            //返回对象引用
};
var obj1 = createObject('Lee', 100);          //创建第一个对象
var obj2 = createObject('Jack', 200);          //创建第二个对象
//alert(obj1.run());                          //打印第一个对象实例的run()方法
//alert(obj2.run());                          //打印第二个对象实例的run()方法

//alert(typeof obj1);
//alert(typeof obj2);
alert(obj1 instanceof Object); //true
alert(obj2 instanceof Object); //true

Copy after login

通过工厂模式创建的对象,解决了重复实例化问题,但对象识别问题无法解决(所有对象均是Object),因此要想解决对象识别问题,我们采用下面的构造函数。

2、构造函数

//构造函数创建
function Person(name,age){  //所有构造函数对象都是Object
  this.name=name;
  this.age=age;
  this.run=function(){
    return this.name+this.age+"ing...";
  };
};
var person1=new Person('zhu1',100);
var person2=new Person('zhu2',200);
alert(person1.run());
alert(person2.run());

alert(person1 instanceof Object); //ture
alert(typeof person2);         //Person
alert(person2 instanceof Person);  // true
var person3=new Object();
Person.call(person3,'zhu3',300);//对象冒充,person3是Object类型,冒充Person类型
alert(person3.run()); 

Copy after login

构造函数中this:代表当前作用域对象的引用,如果在全局范围this代表window对象,如果在构造函数体内,就代表当前构造函数所声明的对象。

构造函数方法,及解决了重复实例化问题,有解决了对象识别问题,对比跟工厂方法不同之处可知:

1.构造函数方法没有显示的创建对象(new Object());

2.直接将属性和方法值赋值给this;

3.没有return 语句;

4.但是使用构造函数创建必须使用new运算符;

以上所述就是本文的全部内容了,希望大家能够喜欢。

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!