javascript 面向对象 new 关键字 原型链 构造函数

6次阅读

共计 1394 个字符,预计需要花费 4 分钟才能阅读完成。

JavaScript 面向对象 JavaScript 语言使用构造函数(constructor)作为对象的模板。所谓”构造函数”,就是专门用来生成实例对象的函数。它就是对象的模板,描述实例对象的基本结构。一个构造函数,可以生成多个实例对象,这些实例对象都有相同的结构

构造函数的首字母大写,区分一般函数。
函数体内部使用了 this 关键字,代表了所要生成的对象实例。
生成对象的时候,必须使用 new 命令。
构造函数内部使用严格模式 ‘use strict’,防止当做一般函数调用,这样就会报错。

function Person(name, age, sex) {
‘use strict’;
this.name = name;
this.age = age;
this.sex = sex;
}

Person() 报错
new Person(“zhangxc”, 29, “male”);
1、new 关键字 命令内部实现
function _new(constructor, params) {// 接受个数不确定参数,第一个参数:构造函数;第二个到第 n 个参数:构造函数传递的参数。
// 1. 首先将参数组成一个数组
// 首先 .slice 这个方法在不接受任何参数的时候会返回 this 本身,这是一个 Array.prototype 下的方法,因此 this 就是指向调用 .slice 方法的数组本身。
var args = Array.prototype.slice.call(arguments); // arguments 伪数组,获取函数的所有参数的伪数组。
// 等价于
// [].slice.call(arguments);
// 2. 获取构造函数
var constructor = args.shift(); // shift() 返回数组第一个元素
// 3. 使用构造函数原型创建一个对象。我们希望以这个现有的对象作为模板,生成新的实例对象,这时就可以使用 Object.create() 方法。
var context = Object.create(constructor.prototype); // Object.create() 参数是一个对象,新建的对象继承参数对象的所有属性
// 4. 将参数属性附加到对象上面
var result = constructor.apply(context, args);
// 5. 返回一个对象
return (typeof result === ‘object’ && result != null) ? result : context;
}

function Person(name, age, sex) {
this.name = name;
this.age = age;
this.sex = sex;
}

var args1 = _new(Person, “zhangxc”, 18, “male”);

// {name: “zhangxc”, age: 18, sex: “male”}

var args2 = new Person(“zhangxc”, 18, “male”);

// {name: “zhangxc”, age: 18, sex: “male”}

new.target 属性
如果当前函数是 new 命令调用,new.target 指向当前函数 (构造函数的名称),否则为 undefined。
function Test() {
console.log(new.target === Test);
}

Test() // false
new Test() // true
2、this 关键字 …3、对象的继承 … 待完善

正文完
 0