JavaScript中的prototype和constructor简明总结_基础知识

WBOY
Release: 2016-05-16 16:53:20
Original
1150 people have browsed it

一、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

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!