<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
<title></title>
<script src="jquery-1.9.1.js"></script>
<meta charset="utf-8" />
</head>
<body>
<button id="btn">提交</button>
</body>
<script>
$('#btn').click(function(){
//通过object创建对象
var person =new Object();
person.name='wj';
person.job='c#.net';
person.fn=function(){
console.log(this.name+this.job);
};
// person.fn();
//通过字面量创建对象
var conmpany={
name:"fanyaunwang",
salary:"6500",
fn:function(){
console.log(this.name+this.salary);
}
};
//conmpany.fn();
//以上2种方式创建对象,会产生大量的重复代码
//通过工厂模式创建对象
// 工厂模式减少了代码重复,但是不能识别对象,所有的实例都是object类型
function createObject(name,age,job)
{
var o = new Object();
o.name=name;
o.age=age;
o.job=job;
o.fn=function(){
console.log(this.name+this.job+this.age);
}
return o;
}
//var wj=createObject('wj','22','c#.net');
//wj.fn();
//通过构造函数创建对象
//构造函数中首字母大写,而非构造函数首字母小写作为区别
function CreatePerson(name,age,job)
{
this.name=name;
this.age=age;
this.job=job;
this.fn=function(){
console.log(this.name+this.age+this.job);
}
}
//通过new来创建CreatePerson实例,这样创建的实例都有一个constractor
//属性指向CreatePerson
//通过工厂模式创建的对象都是object,无法判读对象的类型,
//但是通过构造函数创建的对象可以,这是构造函数创建对象胜过
//通过工厂模式创建对象的地方
var obi=new CreatePerson('wangjun','23','c#.net');
obi.fn();
console.log(obi.constructor==CreatePerson);//true
//通过原型模式来创建对象
//原型模式就是在构造函数中吧方法拿出来的基础上,在做了一层封装
function Employee(){
}
Employee.prototype.name='wangjun';
Employee.prototype.age='c#';
Employee.prototype.fn=function(){
console.log(this.name+this.age);
}
var emp=new Employee();
var emp1=new Employee();
emp.fn();
emp1.fn();
//这个fn是公共的
console.log(emp.fn()==emp1.fn());//true
//在构造函数创建对象的模式中是false
//构造函数和原型混合模式
//创建自定义类型的最常见方式
//构造函数模式用于定义实例属性,
//原型模式用于定义公共属性
function Customer(name,address)
{
this.name=name;
this.address=address;
this.phone=['13946','44848484'];
}
Customer.prototype={
constructor:Customer,
p:['af','sfasf'],
fnn:function(){
console.log(this.name+'prototype');
}
}
var objc= new Customer('fanyuanwang','shenzheng');
var obje=new Customer('wangjin','changsha');
console.log(objc.phone==obje.phone);//false
//上面这个就是构造函数的引用类型的不同
objc.fnn();
console.log(objc.fnn==obje.fnn);//true
objc.fnn();
});
</script>
Javascript创建对象的方法
原创
©著作权归作者所有:来自51CTO博客作者WangJunZzz的原创作品,请联系作者获取转载授权,否则将追究法律责任
上一篇:JavaScript疑难点
下一篇:JQuery学习系列篇(二)
提问和评论都可以,用心的回复会被更多人看到
评论
发布评论
相关文章
-
4种用JavaScript创建对象的方法
对象文字,原型,类,工厂函数等
数据 javascript 原型对象 -
redis_exporter监控多个
一、NRedis-Proxy 介绍NRedis-Proxy 是一个Redis中间件服务,第一个Java 版本开源Redis中间件,无须修改业务应用程序任何代码与配置,与业务解耦;以Spring为基础开发自定义标签,让它可配置化,使其更加容易上手;提供RedisServer监控以及自动、收到failover等功能;以netty 作为通信传输工具,让它具有高性能,高并发,可分布式扩展部署等特点,单机器
redis_exporter监控多个 java 监控redis api redis Redis Server