您现在的位置: 万盛学电脑网 >> 程序编程 >> 脚本专题 >> javascript >> 正文

JavaScript中的prototype和constructor简明总结

作者:佚名    责任编辑:admin    更新时间:2022-06-22

 一直没弄清楚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