6.2.4 Object_构造函数 对象

一. 对象的创建

1. 字面量方式创建   #推荐使用这种方式

 key:value

var stu = {

  name:'alex',

  age:22

}

console.log(stu)

console.log(window)

//点语法 包括get方法和set方法

var n = stu.name

console.log(n)

 

stu.age=44;

console.log(stu.age)

 

2. 使用Object()创建对象

function add(){

}

add()

Object() 构造函数 

1. 首字母大写 碰见构造函数 要想创建对象new

2. 构造函数不需要写return

3. 为对象添加成员变量:this.name = 'alex'

var obj = new Object();

obj.name='xxx'

console.log(obj)

 

var stu=function(){

  this.name = 'xx';

  this.age=14;

  this.fav=function(){

    console.log('泡xx')

  }

}

var s = new stu();

console.log(s)

 

推荐大家使用的构造函数的方式

function Animal(){

  this.name = 'xx';

  this.age=12

//  this.fav = function(){

//    console.log(this.age)

//  }

}

 

Animal.prototype.showname=function(){

  alert(this.name)

  //执行相应的操作

}

 

Animal.prototype.showname2=function(){

  alert(this.name)

  //执行相应的操作

}

var a = new Animal()

a.showname()

 

posted @ 2018-07-21 09:49  beallaliu  阅读(117)  评论(0编辑  收藏  举报