constructor属性
constructor属性
constructor属性是啥
constructor属性用于返回创建该对象的函数,也就是我们常说的构造函数。
语法
Object.constructor
返回值
返回创建该对象的函数的引用
例子
native code 是JavaScript的底层内部代码实现,无法显示代码细节。
-
字符串
var str = "张三" str.constuctor // ƒ String() { [native code] }
-
数组
var arr = [1,2,3] arr.constuctor // ƒ Array() { [native code] }
-
数字
var num = 5 num.constuctor // ƒ Number() { [native code] }
-
自定义对象
function Person(){ this.name = 'kihyun' } var p = new Person(); p.constructor // ƒ Person(){ // this.name = 'kihyun' // }
-
JSON对象
var o = {"name":"kihyun"} o.constructor // ƒ Object() { [native code] }
-
自定义函数
function foo() { alert('nihou') } foo.constructor // ƒ Function() { [native code] }
-
函数的原型
function bar(){ alert('nihou') } bar.prototype.constructor // ƒ bar(){ // alert('nihou') // } // bar的原型的构造函数就是自己
面试题
function Fn() {
this.m = 20
this.a = function(){
console.log(this.m)
}
};
var f1 = new Fn;
Fn.prototype = {
a:function() {
console.log(this.m + 10)
}
};
var f2 = new Fn;
console.log(f1.constructor);
console.log(f2.constructor);
f1.constructor:
function Fn() {
this.m = 20
this.a = function(){
console.log(this.m)
}
};f1相当于上面例子的第4条,是自定义对象
f2.constructor:
ƒ Object() { [native code] }
f2的构造函数增加了prototype中的属性,变成了JSON对象,所以显示为Object(第5条)