展会信息港展会大全

JavaScript中的prototype和constructor简明总结
来源:互联网   发布日期:2016-01-26 10:59:26   浏览:1463次  

导读:一直没弄清楚JavaScript中的prototype和constructor属性,今天看了看书,总算有点眉目了一、constructorconstructor的值是一个函数。在JavaScript中,除了null和undefined外的类型的值、数组、函数以及对象,都有 ...

一直没弄清楚JavaScript中的prototype和constructor属性,今天看了看书,总算有点眉目了

一、constructor

constructor的值是一个函数。在JavaScript中,除了null和undefined外的类型的值、数组、函数以及对象,都有一个constructor属性,constructor属性的值是这个值、数组、函数或者对象的构造函数。如:

代码如下:var a = 12, // 数字

b = 'str', // 字符串

c = false, // 布尔值

d = [1, 'd', function() { return 5; }], // 数组

e = { name: 'e' }, // 对象

f = function() { return 'function'; }; // 函数

console.log('a: ', a.constructor); // Number()

console.log('b: ', b.constructor); // String()

console.log('c: ', c.constructor); // Boolean()

console.log('d: ', d.constructor); // Array()

console.log('e: ', e.constructor); // Object()

console.log('f: ', f.constructor); // Function()

以上的构造函数都是JavaScript内置的,我们也可以自定义构造函数,如:

代码如下:

function A(name) {

this.name = name;

}

var a = new A('a');

console.log(a.constructor); // A(name)

调用构造函数时,需要用new关键字,构造函数返回的是一个对象,看下面的代码就知道了:

代码如下:var a = 4;

var b = new Number(4);

console.log('a: ', typeof a); // a: number

console.log('b: ', typeof b); // b: object

二、 prototype

prototype是函数的一个属性,默认情况下,一个函数的prototype属性的值是一个与函数同名的空对象,匿名函数的 prototype属性名为Object。如:

代码如下:function fn() {}

console.log(fn.prototype); // fn { }

prototype属性主要用来实现JavaScript中的继承,如:

代码如下:function A(name) {

this.name = name;

}

A.prototype.show = function() {

console.log(this.name);

};

function B(name) {

this.name = name;

}

B.prototype = A.prototype;

var test = new B('test');

test.show(); // test

这儿有一个问题,test的构造函数其实是A函数而不是B函数:

代码如下:console.log(test.constructor); // A(name)

这是因为B.prototype = A.prototype把B.prototype的构造函数改成了A,所以需要还原B.prototype的构造函数:

代码如下:function A(name) {

this.name = name;

}

A.prototype.show = function() {

console.log(this.name);

};

function B(name) {

this.name = name;

}

B.prototype = A.prototype;

B.prototype.constructor = B;

var test = new B('test');

test.show(); // test

console.log(test.constructor); // B(name)

之所以要这么做,是因为prototype的值是一个对象,且它的构造函数也就是它的constructor属性的值就是它所在的函数,即:

代码如下:console.log(A.prototype.constructor === A); // true

赞助本站

人工智能实验室

相关热词: prototype constructor JavaScri

AiLab云推荐
展开

热门栏目HotCates

Copyright © 2010-2024 AiLab Team. 人工智能实验室 版权所有    关于我们 | 联系我们 | 广告服务 | 公司动态 | 免责声明 | 隐私条款 | 工作机会 | 展会港