js对象

1. 声明类


 

 1 //这是一个包含方法的类的构造方法
 2 function User(forename,username,password){
 3     this.forename = forename;
 4     this.username = username;
 5     this.password = password;
 6 
 7     this.showUser = function(){
 8         // code here
 9     }
10 }
11 //还可以引用构造方法之外定义的函数
12 function showUser2 = function(){
13     //code here
14 }

2. 创建对象和访问对象


 

 1 //创建一个User类的实例
 2 details = new User("Wolf","aaaa","123456");
 3 
 4 //也可以创建空对象再赋值
 5 details = new User();
 6 details.forename="Wolf";
 7 details.username="aaaa";
 8 details.password="123456";
 9 
10 //也可以为对象添加新的属性
11 details.greeting = "Hello";
12 
13 //访问对象
14 var name = details.username;

3. prototype(原型)关键字


 

  目的:prototype可以节约很多内存空间,在User类中,每个实例包含三个属性和方法。因此,如果内存中有1000个这样的对象,方法showUser将会重复1000次。然而,因为方法在每种情况下都相同,所以可以声明新的变量应该引用方法的单个实例而不是创建它的拷贝。所以,放弃使用:

this.showUser = function()

  使用这个方法来替代:

User.prototype.showUser = function()
 1 //使用prototype关键词为方法声明一个类
 2 function User(forename,username,password){
 3     this.forename = forename;
 4     this.username = username;
 5     this.password = password;
 6 
 7     //使用prototype关键字为方法声明一个类
 8     User.prototype.showUser = function(){
 9         //code here
10     }
11 }

  原理:所有函数都有一个prototype属性,其设计是要拥有来自于类所创建的任何对象中不重复的属性和方法,取而代之的是这些属性和方法通过引用传递给它的对象。

  上面这段话好绕啊……我的理解就是对一个类的所有实例而言,prototype只会创建一个属性或方法引用,而不会生成一个新的拷贝。即是通用的。

 1 //使用prototype关键词为方法声明一个类
 2 function User(forename,username,password){
 3     this.forename = forename;
 4     this.username = username;
 5     this.password = password;
 6 
 7     //使用prototype关键字为方法声明一个类
 8     User.prototype.showUser = function(){
 9         //code here
10     }
11 }
12 var user1 = new User();         //创建一个对象
13 User.prototype.sex = "male";
14 console.log(user1.sex);         //输出为male
15 user1.prototype.mail = "123@163.com";       //报错:Cannot set property 'mail' of undefined。说明对象没有prototype
16 console.log(user1.prototype);   //undefined
17 console.log(User.prototype);    //Object{sex: "male"}

                                                                                                                 

原文地址:https://www.cnblogs.com/haoyijing/p/5742616.html