创建对象,this

86 阅读1分钟

创建一个对象

// 字面量
var obj = {
    name: "xxx",
    age: 18,
};

// 构造函数创建 new 操作符 + Object 创建对象
var obj = new Object();
obj.name = "xxx";
obj.age = 18;

// Object.create() 创建
let obj = Object.create({
    name:"xxx",
    age: 18
})

创建多个对象

// 工厂模式
function students(name,age){
    let obj = {};
    // 添加原料
    obj.name = name;
    obj.age = age;
    // 出厂
    return obj;
}
var obj = students("xxx",18);

// 构造函数
function Students(name,age){
    this.name = name;
    this.age = age;
}
var obj = new Students("xxx",18);

构造函数和工厂模式的区别

 1. 工厂模式没有原型
 2. 没有显式地创建对象,直接将属性和方法赋给了 this 对象
 3. 没有 return 语句

new操作符

 1. 创建 空 对象
 2. 设置原型链( 指向构造函数的原型 )
 3. 改变 构造函数的 this 指向 -- obj
 4. 返回 对象 没有则返回 this

this关键字

 this对象是在运行时基于函数的执行环境绑定的,常见的使用场合如下:
	 1. 在一般函数中this指代全局Window对象
	 2. 作为对象方法调用,this指代上级对象
	 3. 构造函数中,this指代new出的对象
	 4. apply()及call()方法作用是修改函数中this的指向问题

call/apply和bind

apply,call和bind都是 用来改变this的指向

call和apply不同:
    call(obj,args1,args2,...)参数逗号隔开
    apply(obj,[args,args2,...])参数为数组

call/apply和bind不同:
    apply和call会让当前函数立即执行
    bind会返回一个函数,等待调用执行 bind不兼容IE6~8

A.call(B,arg) A的this指向B arg为A的参数

查找属性
1.对象本身找 --> 2. 对象构造函数的 prototype --> 3. Object 的 prototype