js老生常谈之this,constructor ,prototype

2023-11-09 06:38

本文主要是介绍js老生常谈之this,constructor ,prototype,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!

前言

javascript中的this,constructor ,prototype,都是老生常谈的问题,深入理解他们的含义至关重要。在这里,我们再来复习一下吧,温故而知新!

this

this表示当前对象,如果在全局作用范围内使用this,则指代当前页面对象window; 如果在函数中使用this,则this指代什么是根据运行时此函数在什么对象上被调用。 我们还可以使用apply和call两个全局方法来改变函数中this的具体指向。

先看一个在全局作用范围内使用this的例子:

  console.log(this === window);  // trueconsole.log(window.alert === this.alert);  // trueconsole.log(this.parseInt("021", 10));  // 21 

函数中的this是在运行时决定的,而不是函数定义时,如下:

// 定义一个全局函数function foo() {console.log(this.fruit);}// 定义一个全局变量,等价于window.fruit = "apple";var fruit = "apple";// 此时函数foo中this指向window对象// 这种调用方式和window.foo();是完全等价的foo();  // "apple"// 自定义一个对象,并将此对象的属性foo指向全局函数foovar pack = {fruit: "orange",foo: foo};// 此时函数foo中this指向window.pack对象pack.foo(); // "orange"

全局函数apply和call可以用来改变函数中this的指向,如下:

// 定义一个全局函数function foo() {console.log(this.fruit);}// 定义一个全局变量var fruit = "apple";// 自定义一个对象var pack = {fruit: "orange"};// 等价于window.foo();foo.apply(window);  // "apple"// 此时foo中的this === packfoo.apply(pack);    // "orange"

注:apply和call两个函数的作用相同,唯一的区别是两个函数的参数定义不同。

因为在JavaScript中函数也是对象,所以我们可以看到如下有趣的例子:

// 定义一个全局函数function foo() {if (this === window) {console.log("this is window.");}}// 函数foo也是对象,所以可以定义foo的属性boo为一个函数foo.boo = function() {if (this === foo) {console.log("this is foo.");} else if (this === window) {console.log("this is window.");}};// 等价于window.foo();foo();  // this is window.// 可以看到函数中this的指向调用函数的对象foo.boo();  // this is foo.// 使用apply改变函数中this的指向foo.boo.apply(window);  // this is window.

prototype

prototype本质上还是一个JavaScript对象。

并且每个函数都有一个默认的prototype属性。如果这个函数被用在创建自定义对象的场景中,我们称这个函数为构造函数。 比如下面一个简单的场景:

// 构造函数function Person(name) {this.name = name;}// 定义Person的原型,原型中的属性可以被自定义对象引用Person.prototype = {getName: function() {return this.name;}}var hao= new Person("haorooms");console.log(hao.getName());   // "haorooms"

作为类比,我们考虑下JavaScript中的数据类型 - 字符串(String)、数字(Number)、数组(Array)、对象(Object)、日期(Date)等。

我们有理由相信,在JavaScript内部这些类型都是作为构造函数来实现的,比如:

// 定义数组的构造函数,作为JavaScript的一种预定义类型function Array() {// ...}// 初始化数组的实例var arr1 = new Array(1, 56, 34, 12);// 但是,我们更倾向于如下的语法定义:var arr2 = [1, 56, 34, 12];

同时对数组操作的很多方法(比如concat、join、push)应该也是在prototype属性中定义的。 实际上,JavaScript所有的固有数据类型都具有只读的prototype属性(这是可以理解的:因为如果修改了这些类型的prototype属性,则哪些预定义的方法就消失了),但是我们可以向其中添加自己的扩展方法。

// 向JavaScript固有类型Array扩展一个获取最小值的方法Array.prototype.min = function() {var min = this[0];for (var i = 1; i < this.length; i++) {if (this[i] < min) {min = this[i];}}return min;};// 在任意Array的实例上调用min方法console.log([1, 56, 34, 12].min());  // 1

注意:这里有一个陷阱,向Array的原型中添加扩展方法后,当使用for-in循环数组时,这个扩展方法也会被循环出来。 下面的代码说明这一点(假设已经向Array的原型中扩展了min方法):

 var arr = [1, 56, 34, 12];var total = 0;for (var i in arr) {total += parseInt(arr[i], 10);}console.log(total);   // NaN

解决方法也很简单:

var arr = [1, 56, 34, 12];var total = 0;for (var i in arr) {if (arr.hasOwnProperty(i)) {total += parseInt(arr[i], 10);}}console.log(total);   // 103

constructor

constructor始终指向创建当前对象的构造函数。比如下面例子:

// 等价于 var foo = new Array(1, 56, 34, 12);var arr = [1, 56, 34, 12];console.log(arr.constructor === Array); // true// 等价于 var foo = new Function();var Foo = function() { };console.log(Foo.constructor === Function); // true// 由构造函数实例化一个obj对象var obj = new Foo();console.log(obj.constructor === Foo); // true// 将上面两段代码合起来,就得到下面的结论console.log(obj.constructor.constructor === Function); // true

但是当constructor遇到prototype时,有趣的事情就发生了。 我们知道每个函数都有一个默认的属性prototype,而这个prototype的constructor默认指向这个函数。如下例所示:

function Person(name) {this.name = name;};Person.prototype.getName = function() {return this.name;};var p = new Person("haorooms");console.log(p.constructor === Person);  // trueconsole.log(Person.prototype.constructor === Person); // true// 将上两行代码合并就得到如下结果console.log(p.constructor.prototype.constructor === Person); // true

当时当我们重新定义函数的prototype时(注意:和上例的区别,这里不是修改而是覆盖),constructor的行为就有点奇怪了,如下示例:

function Person(name) {this.name = name;};Person.prototype = {getName: function() {return this.name;}};var p = new Person("haorooms");console.log(p.constructor === Person);  // falseconsole.log(Person.prototype.constructor === Person); // falseconsole.log(p.constructor.prototype.constructor === Person); // false

为什么呢? 原来是因为覆盖Person.prototype时,等价于进行如下代码操作:

Person.prototype = new Object({getName: function() {return this.name;}});

而constructor始终指向创建自身的构造函数,所以此时Person.prototype.constructor === Object,即是:

function Person(name) {this.name = name;};Person.prototype = {getName: function() {return this.name;}};var p = new Person("haorooms");console.log(p.constructor === Object);  // trueconsole.log(Person.prototype.constructor === Object); // trueconsole.log(p.constructor.prototype.constructor === Object); // true

怎么修正这种问题呢?方法也很简单,重新覆盖Person.prototype.constructor即可:

function Person(name) {this.name = name;};Person.prototype = {getName: function() {return this.name;}};Person.prototype.constructor = Person;var p = new Person("haorooms");console.log(p.constructor === Person);  // trueconsole.log(Person.prototype.constructor === Person); // trueconsole.log(p.constructor.prototype.constructor === Person); // true

也可以这么写:

function Person(name) {this.name = name;};Person.prototype = {constructor:Person,//指定constructorgetName: function() {return this.name;}};

这篇关于js老生常谈之this,constructor ,prototype的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



http://www.chinasem.cn/article/374503

相关文章

JS常用组件收集

收集了一些平时遇到的前端比较优秀的组件,方便以后开发的时候查找!!! 函数工具: Lodash 页面固定: stickUp、jQuery.Pin 轮播: unslider、swiper 开关: switch 复选框: icheck 气泡: grumble 隐藏元素: Headroom

在JS中的设计模式的单例模式、策略模式、代理模式、原型模式浅讲

1. 单例模式(Singleton Pattern) 确保一个类只有一个实例,并提供一个全局访问点。 示例代码: class Singleton {constructor() {if (Singleton.instance) {return Singleton.instance;}Singleton.instance = this;this.data = [];}addData(value)

Node.js学习记录(二)

目录 一、express 1、初识express 2、安装express 3、创建并启动web服务器 4、监听 GET&POST 请求、响应内容给客户端 5、获取URL中携带的查询参数 6、获取URL中动态参数 7、静态资源托管 二、工具nodemon 三、express路由 1、express中路由 2、路由的匹配 3、路由模块化 4、路由模块添加前缀 四、中间件

EasyPlayer.js网页H5 Web js播放器能力合集

最近遇到一个需求,要求做一款播放器,发现能力上跟EasyPlayer.js基本一致,满足要求: 需求 功性能 分类 需求描述 功能 预览 分屏模式 单分屏(单屏/全屏) 多分屏(2*2) 多分屏(3*3) 多分屏(4*4) 播放控制 播放(单个或全部) 暂停(暂停时展示最后一帧画面) 停止(单个或全部) 声音控制(开关/音量调节) 主辅码流切换 辅助功能 屏

使用JS/Jquery获得父窗口的几个方法(笔记)

<pre name="code" class="javascript">取父窗口的元素方法:$(selector, window.parent.document);那么你取父窗口的父窗口的元素就可以用:$(selector, window.parent.parent.document);如题: $(selector, window.top.document);//获得顶级窗口里面的元素 $(

js异步提交form表单的解决方案

1.定义异步提交表单的方法 (通用方法) /*** 异步提交form表单* @param options {form:form表单元素,success:执行成功后处理函数}* <span style="color:#ff0000;"><strong>@注意 后台接收参数要解码否则中文会导致乱码 如:URLDecoder.decode(param,"UTF-8")</strong></span>

js react 笔记 2

起因, 目的: 记录一些 js, react, css 1. 生成一个随机的 uuid // 需要先安装 crypto 模块const { randomUUID } = require('crypto');const uuid = randomUUID();console.log(uuid); // 输出类似 '9b1deb4d-3b7d-4bad-9bdd-2b0d7b3dcb6d'

学习记录:js算法(二十八):删除排序链表中的重复元素、删除排序链表中的重复元素II

文章目录 删除排序链表中的重复元素我的思路解法一:循环解法二:递归 网上思路 删除排序链表中的重复元素 II我的思路网上思路 总结 删除排序链表中的重复元素 给定一个已排序的链表的头 head , 删除所有重复的元素,使每个元素只出现一次 。返回 已排序的链表 。 图一 图二 示例 1:(图一)输入:head = [1,1,2]输出:[1,2]示例 2:(图

uuid.js 使用

相关代码 import { NIL } from "uuid";/** 验证UUID* 为空 则返回 false* @param uuid* @returns {boolean}*/export function MyUUIDValidate(uuid: any): boolean {if (typeof uuid === "string" && uuid !== NIL) { //uuid

js定位navigator.geolocation

一、简介   html5为window.navigator提供了geolocation属性,用于获取基于浏览器的当前用户地理位置。   window.navigator.geolocation提供了3个方法分别是: void getCurrentPosition(onSuccess,onError,options);//获取用户当前位置int watchCurrentPosition(