javascript中的constructor
2024-08-27 21:04:16
constructor,构造函数,对这个名字,我们都不陌生,constructor始终指向创建当前对象的构造函数。
这里有一点需要注意的是,每个函数都有一个prototype属性,这个prototype的constructor指向这个函数,这个时候我们修改这个函数的prototype时,就发生了意外。如
function Person(name,age){
this.name = name;
this.age = age;
} Person.prototype.getAge = function(){
return this.age;
}
Person.prototype.getName = function(){
return this.name;
} var p = new Person("Nicholas",18);
console.log(p.constructor); //Person(name, age)
console.log(p.getAge()); //
console.log(p.getName()); //Nicholas
但是如果是这样:
function Person(name,age){
this.name = name;
this.age = age;
} Person.prototype = {
getName:function(){
return this.name;
},
getAge:function(){
return this.age;
}
} var p = new Person("Nicholas",18);
console.log(p.constructor); //Object()
console.log(p.getAge()); //
console.log(p.getName()); //Nicholas
结果constructor变了。
原因就是prototype本身也是对象,上面的代码等价于
Person.prototype = new Object({
getName:function(){
return this.name;
},
getAge:function(){
return this.age;
}
});
因为constructor始终指向创建当前对象的构造函数,那么就不难理解上面代码p.constructor输出的是Object了。
对于修改了prototype之后的constructor还想让它指向Person怎么办呢?简单,直接给Person.prototype.constructor赋值就可以了:
Person.prototype = {
constructor:Person,
getName:function(){
return this.name;
},
getAge:function(){
return this.age;
}
}
最新文章
- 11g新特性-使用DNFS
- boost和std中的thread的引用参数
- LINQ的All的方法
- [转]Python格式化输出
- [Effective JavaScript 笔记]第54条:将undefined看做“没有值”
- 黄聪:走进wordpress do_action函数
- maven项目在tomcat中运行遇到的问题
- android 删除的警告对话框
- 检查ORACLE的警告文件的脚本
- CVE-2014-4115漏洞分析(2014.11)
- 安装oracle后不能连接问题
- border-radius IE8兼容处理
- Javascript数组(1)--基本属性及方法
- (七)php运算符
- Swift类中如何创建一个对外只读对内可读写的属性
- python之面向对象初识
- 源码包安装apache
- 这不是我想要的ABAP开发者
- Vue Router的入门以及简单使用
- classlist和array.prototype.slice.call
热门文章
- MDI设置父子窗体
- vue中moment.js的使用
- foobox,基于foobar2000汉化版的CUI配置整合版
- foobox更新日志
- ElegantSnap 一个优雅的,易用的iOS/tvOS/macOS自动布局框架, 超级详细的使用教程,多视图水平等宽/垂直等高排列
- Untargeted lipidomics reveals specific lipid abnormality in nonfunctioning human pituitary adenomas 非靶向脂质组学揭示非功能人类脑垂体瘤中的特异性脂质 (解读人:胡丹丹)
- F-NAScan:一款网络资产扫描工具
- python中使用openpyxl模块时报错: File is not a zip file
- jQuery常用事件,each循环,引用当前时间
- 从源码和doc揭秘——Java中的Char究竟几个字节,Java与Unicode的关系