栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > Web开发 > JavaScript

JavaScript中的prototype和constructor简明总结

JavaScript 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

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

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/107579.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号