JavaScript——this、constructor、prototype
this
this表示当前对象,如果在全局作用范围内使用this,则指代当前页面对象window; 如果在函数中使用this,则this指代什么是根据运行时此函数在什么对象上被调用。 我们还可以使用apply和call两个全局方法来改变函数中this的具体指向。
先看一个在全局作用范围内使用this的例子:
<script type="text/javascript">
console.log(this === window); // true
console.log(window.alert === this.alert); // true
console.log(this.parseInt("021", 10)); // 10
</script>
函数中的this是在运行时决定的,而不是函数定义时,如下:
// 定义一个全局函数
function foo() {
console.log(this.fruit);
}
// 定义一个全局变量,等价于window.fruit = "apple";
var fruit = "apple";
// 此时函数foo中this指向window对象
// 这种调用方式和window.foo();是完全等价的
foo(); // "apple" // 自定义一个对象,并将此对象的属性foo指向全局函数foo
var 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 === pack
foo.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模拟类和继承的实现。 prototype本质上还是一个JavaScript对象。 并且每个函数都有一个默认的prototype属性。
如果这个函数被用在创建自定义对象的场景中,我们称这个函数为构造函数。 比如下面一个简单的场景:
// 构造函数
function Person(name) {
this.name = name;
}
// 定义Person的原型,原型中的属性可以被自定义对象引用
Person.prototype = {
getName: function() {
return this.name;
}
}
var zhang = new Person("ZhangSan");
console.log(zhang.getName()); // "ZhangSan"
作为类比,我们考虑下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("ZhangSan"); console.log(p.constructor === Person); // true
console.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("ZhangSan");
console.log(p.constructor === Person); // false
console.log(Person.prototype.constructor === Person); // false
console.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("ZhangSan");
console.log(p.constructor === Object); // true
console.log(Person.prototype.constructor === Object); // true
console.log(p.constructor.prototype.constructor === Object); // true
怎么修正这种问题呢?方法也很简单,重新覆盖Person.prototype.constructor即可:
function Person(name) {
this.name = name;
};
Person.prototype = new Object({
getName: function() {
return this.name;
}
});
Person.prototype.constructor = Person;
var p = new Person("ZhangSan");
console.log(p.constructor === Person); // true
console.log(Person.prototype.constructor === Person); // true
console.log(p.constructor.prototype.constructor === Person); // true
JavaScript——this、constructor、prototype的更多相关文章
- 关于JS call apply 对象、对象实例、prototype、Constructor、__proto__
关于call与apply的理解容易让人凌乱,这里有个方法可供参考 tiger.call(fox,arg1,arg2...) tiger.apply(fox,[arg1,arg2...]) 理解为 fo ...
- 深入理解__proto__ 、constructor和prototype的关系
深入理解__proto__ .constructor和prototype的关系 2013-11-12 09:56 1390人阅读 评论(3) 收藏 举报 分类: 前端之Javascript(59) ...
- 面向对象的程序设计(二)理解各种方法和属性typeof、instanceof、constructor、prototype、__proto__、isPrototypeOf、hasOwnProperty
//理解各种方法和属性typeof.instanceof.constructor.prototype.__proto__.isPrototypeOf.hasOwnProperty. //1.typeo ...
- javascript 中isPrototypeOf 、hasOwnProperty、constructor、prototype等用法
hasOwnProperty:是用来判断一个对象是否有你给出名称的属性或对象,此方法无法检查该对象的原型链中是否具有该属性,该属性必须是对象本身的一个成员. isPrototypeOf是用来判断要检查 ...
- Js中Prototype、__proto__、Constructor、Object、Function关系介绍
一. Prototype.__proto__与Object.Function关系介绍 Function.Object:都是Js自带的函数对象.prototype,每一个函数对象都有一个显式的proto ...
- 【转】Js中Prototype、__proto__、Constructor、Object、Function关系介绍
一 Prototype.__proto__与Object.Function关系介绍 Function.Object:Js自带的函数对象. prototype,每一个 ...
- JS中关于构造函数、原型链、prototype、constructor、instanceof、__proto__属性
在Javascript不存在类(Class)的概念,javascript中不是基于类的,而是通过构造函数(constructor)和原型链(prototype chains)实现的.但是在ES6中引入 ...
- 第197天:js---caller、callee、constructor和prototype用法
一.caller---返回函数调用者 //返回函数调用者 //caller的应用场景 主要用于察看函数本身被哪个函数调用 function fn() { //判断某函数是否被调用 if (fn.cal ...
- 【转】JavaScript中的constructor与prototype
最初对js中 object.constructor 的认识: 在学习JS的面向对象过程中,一直对constructor与prototype感到很迷惑,看了一些博客与书籍,觉得自己弄明白了,现在记录如下 ...
随机推荐
- 表达式拼接Expression<Func<IEntityMapper, bool>> predicate
/// <summary> /// 重写以筛选出当前上下文的实体映射信息 /// </summary> protected override IEnumerable<IE ...
- Python之路【第三篇】:Python基础(二)
函数的理解 面向过程:根据业务逻辑从上到下写垒代码 函数式:将某功能代码封装到函数中,日后便无需重复编写,仅调用函数即可 函数作用是你的程序有良好的扩展性.复用性. 同样的功能要是用3次以上的话就建议 ...
- php如何发起POST DELETE GET POST 请求
关于POST,DELETE,GET,POST请求 get:是用来取得数据.其要传递过的信息是拼在url后面,因为其功能使然,有长度的限制 post:是用来上传数据.要上传的数据放在request的he ...
- 后缀.jar的是什么文件?
解压kafka 打开后是一堆.jar结尾的文件,那么后缀.jar的是什么文件? JAR 文件就是 Java Archive File,顾名思意,它的应用是与 Java 息息相关的,是 Java 的一种 ...
- 如何在html中做圆角矩形和 只有右边的"分隔线"
这个网站满好的,可以常看看 css-matic中有几个很好的写css可视化的工具 其实做css 版式布局等都可以有工具的 推荐40个优秀的免费CSS工具 debugger正则表达式在线 其实是对(理论 ...
- 梳理javascript原型整体思路
相信很多对javascript原型初步了解的人都知道prototype,constructor,__proto__这些名词,也在一定程度上可以使用这些对象.属性.甚至知道在构造函数的原型上定义方法供实 ...
- NetBeans使用习惯:升级与保存配置
如何升级:点击 netbeans 的升级更新 ,即可升级版本:不推荐官网下载进行安装,否则会出现,以前的旧版本8.0的目录和8.0.1目录,虽然它会自动检测到以前版本的配置,提示导入... 如何备份: ...
- Java-Linux系统中搭建开发环境
准备工作: 0.虚拟机中的系统→{RHEL-I386} 1.JDK→{首先要知道下载哪个版本" [zf@string ~]$ getconf LONG_BIT ":".t ...
- mysql 总结二(自定义函数)
本质:mysql内置函数的一种扩展,本质上与mysql内置函数一样. 函数必要条件: @1:参数(非必备): @2:返回值: 模板: create function function_name ret ...
- linux配置java环境变量
linux配置java环境变量(详细) 一. 解压安装jdk 在shell终端下进入jdk-6u14-linux-i586.bin文件所在目录, 执行命令 ./jdk-6u14-linux-i586. ...