js中四种创建对象的方式

一、

1 var user = new Object();
2 user.first="Brad";
3 user.last="Dayley";
4 user.getName = function( ) { return this.first + " " + this.last; }

二、

1 var user = {
2   first: 'Brad',
3   last: 'Dayley',
4   getName: function( ) { return this.first + " " + this.last; }};

 三、

 1 function zch(first, last) {
 2     this.first = first;
 3     this.last = last;
 4     this.getName = function () {
 5         return this.first + " " + this.last;
 6     };
 7 }
 8 
 9 var user = new zch("zheng", "chunhao");
10 console.log(user.getName());

 四、

 1 function User(first, last){
 2     this.first = first;
 3     this.last = last;
 4 }
 5 User.prototype = {
 6     getFullName: function(){
 7         return this.first + " " + this.last;
 8     },
 9     sayHello: function(){
10         console.log('hello,zhengchunhao.');
11     }
12 };
13 
14 var zch = new User("zheng", "chunhao");
15 console.log(zch.getFullName());
16 
17 zch.sayHello();
原文地址:https://www.cnblogs.com/zhengchunhao/p/4977658.html