JS - Constructor还可以这样用

时间:2022-09-29 15:28:52

JS中Constructor好用法:

即在只知道一个对象实例的情况下(不知道对象名),重新初始化一个新实例;

 function Person( firstname, lastname, age ) {
  this.firstname = firstname;
  this.lastname = lastname;
4   this.age = age;
} var dave = new Person("Dave", "Smith", 28); document.write( dave.constructor + "<br />");
// function Person(firstname, lastname, age) { this.firstname = firstname; this.lastname = lastname; this.age = age; } // we can create a new object from another object's constructor:
var mike = new dave.constructor("Mike", "Fox", 22); // Is mike an instance of the Person object?
document.write( mike.constructor == Person ); // true