Can we cast a generic object to a custom object type in javascript?

后端 未结 6 1309
暖寄归人
暖寄归人 2021-01-31 13:46

For example, I already have this object somewhere in the code, it is a generic object:

var person1={lastName:\"Freeman\",firstName:\"Gordon\"};

6条回答
  •  遥遥无期
    2021-01-31 14:10

    No.

    But if you're looking to treat your person1 object as if it were a Person, you can call methods on Person's prototype on person1 with call:

    Person.prototype.getFullNamePublic = function(){
        return this.lastName + ' ' + this.firstName;
    }
    Person.prototype.getFullNamePublic.call(person1);
    

    Though this obviously won't work for privileged methods created inside of the Person constructor—like your getFullName method.

提交回复
热议问题