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

栏目: JavaScript · 发布时间: 6年前

内容简介:JavaScript面向对象2、this关键字

JavaScript面向对象

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

  1. 构造函数的首字母大写,区分一般函数。
  2. 函数体内部使用了this关键字,代表了所要生成的对象实例。
  3. 生成对象的时候,必须使用new命令。
  4. 构造函数内部使用严格模式 '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、对象的继承

... 待完善


以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持 码农网

查看所有标签

猜你喜欢:

本站部分资源来源于网络,本站转载出于传递更多信息之目的,版权归原作者或者来源机构所有,如转载稿涉及版权问题,请联系我们

Paradigms of Artificial Intelligence Programming

Paradigms of Artificial Intelligence Programming

Peter Norvig / Morgan Kaufmann / 1991-10-01 / USD 77.95

Paradigms of AI Programming is the first text to teach advanced Common Lisp techniques in the context of building major AI systems. By reconstructing authentic, complex AI programs using state-of-the-......一起来看看 《Paradigms of Artificial Intelligence Programming》 这本书的介绍吧!

JSON 在线解析
JSON 在线解析

在线 JSON 格式化工具

HTML 编码/解码
HTML 编码/解码

HTML 编码/解码

HEX CMYK 转换工具
HEX CMYK 转换工具

HEX CMYK 互转工具