温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

JavaScript中constructor属性如何使用

发布时间:2021-07-01 15:44:28 来源:亿速云 阅读:288 作者:Leah 栏目:web开发

这篇文章给大家介绍JavaScript中constructor属性如何使用,内容非常详细,感兴趣的小伙伴们可以参考借鉴,希望对大家能有所帮助。

constructor属性始终指向创建当前对象的构造函数。比如下面例子:

// 等价于 var foo = new Array(1, 56, 34, 12);  var arr = [1, 56, 34, 12];  console.log(arr.constructor === Array); // true  // 等价于 var foo = new Function();  var Foo = function() { };  console.log(Foo.constructor === Function); // true  // 由构造函数实例化一个obj对象  var obj = new Foo();  console.log(obj.constructor === Foo); // true   // 将上面两段代码合起来,就得到下面的结论  console.log(obj.constructor.constructor === Function); // true

但是当constructor遇到prototype时,有趣的事情就发生了。

我们知道每个函数都有一个默认的属性prototype,而这个prototype的constructor默认指向这个函数。如下例所示:

function Person(name) {      this.name = name;  };  Person.prototype.getName = function() {      return this.name;  };  var p = new Person("ZhangSan");   console.log(p.constructor === Person);  // true  console.log(Person.prototype.constructor === Person); // true  // 将上两行代码合并就得到如下结果  console.log(p.constructor.prototype.constructor === Person); // true

当时当我们重新定义函数的prototype时(注意:和上例的区别,这里不是修改而是覆盖),constructor属性的行为就有点奇怪了,如下示例:

function Person(name) {      this.name = name;  };  Person.prototype = {      getName: function() {          return this.name;      }  };  var p = new Person("ZhangSan");  console.log(p.constructor === Person);  // false  console.log(Person.prototype.constructor === Person); // false  console.log(p.constructor.prototype.constructor === Person); // false

为什么呢?

原来是因为覆盖Person.prototype时,等价于进行如下代码操作:

Person.prototype = new Object({      getName: function() {          return this.name;      }  });

而constructor属性始终指向创建自身的构造函数,所以此时Person.prototype.constructor === Object,即是:

function Person(name) {      this.name = name;  };  Person.prototype = {      getName: function() {          return this.name;      }  };  var p = new Person("ZhangSan");  console.log(p.constructor === Object);  // true  console.log(Person.prototype.constructor === Object); // true  console.log(p.constructor.prototype.constructor === Object); // true

怎么修正这种问题呢?方法也很简单,重新覆盖Person.prototype.constructor即可:

function Person(name) {      this.name = name;  };  Person.prototype = new Object({      getName: function() {          return this.name;      }  });  Person.prototype.constructor = Person;  var p = new Person("ZhangSan");  console.log(p.constructor === Person);  // true  console.log(Person.prototype.constructor === Person); // true  console.log(p.constructor.prototype.constructor === Person); // true

关于JavaScript中constructor属性如何使用就分享到这里了,希望以上内容可以对大家有一定的帮助,可以学到更多知识。如果觉得文章不错,可以把它分享出去让更多的人看到。

向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

AI