首页 > Web开发 > 详细

js创建对象的几种方法

时间:2019-03-24 17:18:45      阅读:141      评论:0      收藏:0      [点我收藏+]
1.  json方法
1 var person = {
2             name: ‘xm‘,
3             sex: ‘male‘,
4             action: function () {
5                 console.log(this.name);
6             }
7         };
8         person.action();
9         console.log(person);
输出如下

技术分享图片

 

2. Object方法
1 var person = new Object();
2         person.name = ‘xm‘;
3         person.sex = ‘male‘;
4         person.action = function(){
5             console.log(this.name);
6         };
7         person.action();
8         console.log(person);

技术分享图片

 

3. 构造函数方法

 1 function act(name, sex) {
 2             this.name = name;
 3             this.sex =sex;
 4             this.action = function () {
 5                 console.log(this.name);
 6             }
 7         }
 8         var person = new act(‘xm‘, ‘male‘);
 9         person.action();
10         console.log(person);

 技术分享图片

 

4. 工厂模式

 1 function act(name, sex) {
 2             var obj = new Object();
 3             obj.name = name;
 4             obj.sex = sex;
 5             obj.action = function () {
 6                 console.log(this.name);
 7             };
 8             return obj;
 9         }
10         var person = act(‘xm‘, ‘male‘);
11         person.action();
12         console.log(person);

技术分享图片

 

5.原型模式

 1 function act() {
 2         }
 3         act.prototype.name = ‘xm‘;
 4         act.prototype.sex = ‘male‘;
 5         act.prototype.action = function () {
 6             console.log(this.name);
 7         };
 8         var person = new act();
 9         person.action();
10         console.log(person);

技术分享图片

 

6.混合模式 构造 + 原型

 1 function act(name, sex) {
 2             this.name = name;
 3             this.sex = sex;
 4             this.action = function () {
 5                 console.log(this.name);
 6             };
 7         }
 8         act.prototype = {
 9             friend: ‘xh‘,
10             say: function () {
11                 console.log(this.friend);
12             }
13         };
14         var person = new act(‘xm‘, ‘male‘);
15         person.action();
16         person.say();
17         console.log(person);

技术分享图片

 

js创建对象的几种方法

原文:https://www.cnblogs.com/passerma/p/10588715.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!