【转】js老生常谈之this,constructor ,prototype
前言
javascript中的this,constructor ,prototype,都是老生常谈的问题,深入理解他们的含义至关重要。在这里,我们再来复习一下吧,温故而知新!
this
this表示当前对象,如果在全局作用范围内使用this,则指代当前页面对象window; 如果在函数中使用this,则this指代什么是根据运行时此函数在什么对象上被调用。 我们还可以使用apply和call两个全局方法来改变函数中this的具体指向。
先看一个在全局作用范围内使用this的例子:
1 console.log(this === window); // true 2 console.log(window.alert === this.alert); // true 3 console.log(this.parseInt("021", 10)); // 10
函数中的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;}};
转自:http://www.haorooms.com/post/js_constructor_pro
转载于:https://www.cnblogs.com/cydiacen/p/5354072.html
【转】js老生常谈之this,constructor ,prototype相关推荐
- js老生常谈之this,constructor ,prototype
2019独角兽企业重金招聘Python工程师标准>>> http://www.haorooms.com/post/js_constructor_pro 转载于:https://my. ...
- js(javascript)中__proto__和prototype解析
为什么80%的码农都做不了架构师?>>> __proto__是内部原型,prototype是构造器原型(构造器其实就是函数) 构造器的原型是一个对象 一.所有构造器/函数的__ ...
- JS函数浅析之constructor、prototype属性
函数是JS里很神奇的一位童鞋.那么如何创建一个函数呢?简单来说有下面几种形式: 1.定义式 function a() {} 2.声明式 var a = function ...
- JS 一张图理解prototype、proto和constructor的关系
转载于原文地址:https://www.cnblogs.com/xiaohuochai/p/5721552.html(感谢大神的总结) 前面的话 javascript里的关系又多又乱.作用域链是一种单 ...
- JS面向对象,__proto__和prototype详解
一.类,对象和原型 类是具体事物的抽象,而对象是类的实例.举个例子,学生类可以有nama属性,grade属性,study方法等等,而对于学生类的实例就具体到某一个学生上去了,如name:小红 grad ...
- js中的_poto_和prototype的问题
初学javascript的时候也跟题主一样搞不清楚,自己好好总结了一下: 首先,要明确几个点: 1.在JS里,万物皆对象.方法(Function)是对象,方法的原型(Function.prototyp ...
- JS 面向对象编程之原型(prototype)
微信小程序开发交流qq群 173683895 承接微信小程序开发.扫码加微信. function Person(first, last) {this.first = first;this.l ...
- js数组初始化——ES6 Array.prototype.fill()实践记录
Array.prototype.fil()方法:用给定值填充数组 初始化: let array = new Array(5).fill(false); console.log(array); //显示 ...
- js 箭头函数没有 constructor,不能被new
var fn1 = function(item) {console.log('item---', item) } var fn = (item) => {console.log('item--- ...
最新文章
- fbx 转 gltf glb 文件
- html5自适应团购,基于HTML5的O2O团购平台的设计与实现
- php如何生成html,php生成html文件方法总结
- 今天项目中遇到的一个问题:判断新闻Id是否存在
- 蜗牛星际网卡驱动_矿渣“蜗牛星际“折腾NAS黑群晖全过程
- oracle数据块一致性检查的4种方法
- Centos7 PXE服务器部署
- iOS开发,第三方应用微信授权登录,获取微信unionid
- IT菜鸟最实用的网站,只要不造轮子,都能解决。
- Java + OpenCV 实现图片合成(JavaCV)
- android电视直播卡顿,智能电视或电视盒子经常会在看直播的时候卡顿
- 我的开源项目:C++ Qt高仿QQ影音视频播放器
- Android入门篇
- word图文混排复制到CKEditor图片不显示
- web项目图片/文件保存方式
- win10环境下安装elasticsearch实践
- Linux: 目录和文件
- “通过管理风险与机会,完善质量管理”顶级质量大师质量讲座录音文字稿
- ThreeJS 着色器打造震撼海洋动画
- 《深入理解计算机系统》读书札记(第一章)
热门文章
- 用final关键字修饰一个变量时,是引用不能变,还是引用的对象不能变
- 自定义注解,aop实现注解锁
- mysql 查询时间转换_数据库查询时日期的转换
- 系统设计知识:系统模块结构设计知识笔记
- 收集18个高大上的浏览器小技巧
- [翻译] Visual Studio 2019 RC版发布
- 【收集】C#一些基础的面试题
- 程序员养生攻略,你值得拥有
- configuration 命名空间_kubernetes30:monitoring命名空间处于Terminating状态的处理方法...
- linux中profile文件作用,解析Linux系统中bashrc和profile文件的作用区别