如何从构造函数中访问原型对象?
在下面的Javascript代码中,我有一个Person构造函数,该函数带有两个getter / setter函数,以及在其原型中定义的hydrate函数:
final LOCAL='local'
final DEV='dev'
void configBootTask(Task bootTask, String profile) {
bootTask.main = bootJar.mainClassName
bootTask.classpath = sourceSets.main.runtimeClasspath
bootTask.args = [ "--spring.profiles.active=$profile" ]
// systemProperty 'spring.profiles.active', profile // this approach also may be used
bootTask.environment = postgresLocalEnvironment
}
bootRun {
description "Run Spring boot application with \"$LOCAL\" profile"
doFirst() {
configBootTask(it, LOCAL)
}
}
task bootRunLocal(type: BootRun, dependsOn: 'classes') {
description "Alias to \":${bootRun.name}\" task: ${bootRun.description}"
doFirst() {
configBootTask(it, LOCAL)
}
}
task bootRunDev(type: BootRun, dependsOn: 'classes') {
description "Run Spring boot application with \"$DEV\" profile"
doFirst() {
configBootTask(it, DEV)
}
}
task bootPostgresRunLocal(type: BootRun) {
description "Run Spring boot application with \"$LOCAL\" profile and re-creating DB Postgres container"
dependsOn runPostgresDocker
finalizedBy killPostgresDocker
doFirst() {
configBootTask(it, LOCAL)
}
}
task bootPostgresRunDev(type: BootRun) {
description "Run Spring boot application with \"$DEV\" profile and re-creating DB Postgres container"
dependsOn runPostgresDocker
finalizedBy killPostgresDocker
doFirst() {
configBootTask(it, DEV)
}
}
我想从Person构造函数中调用hydrate()函数,即使这对我来说没有意义,就像在完全创建对象之前调用方法,对吗?如果我错了纠正我。 JavaScript代码:
+++++++++++++++++++++++++++++
+ Person +
+++++++++++++++++++++++++++++
+ setFirstname( firstname ) +
+ getFirstname() +
+ setLastname( lastname ) +
+ getLastname() +
+++++++++++++++++++++++++++++
+++++++++++++++++++++++++++++
+ Person.prototype +
+++++++++++++++++++++++++++++
+ hydrate( person ) +
+++++++++++++++++++++++++++++
结果:
错误:未捕获的TypeError:this.setFirstname不是函数
问题:我该怎么做?那有可能吗?
答案 0 :(得分:0)
为此,我应该更改了hydrate()函数的调用位置,并将其置于底部[在setFirstname()和setLastname()公开可用之后),如下所示:
function Person( person ) {
var _firstname = '',
_lastname ='';
function setFirstname( firstname ) {
_firstname = firstname;
}
function getFirstname() {
return _firstname;
}
function setLastname( lastname ) {
_lastname = lastname;
}
function getLastname() {
return _lastname;
}
this.setFirstname = setFirstname;
this.getFirstname = getFirstname;
this.setLastname = setLastname;
this.getLastname = getLastname;
if ( person ) this.hydrate( person );
}
Person.prototype = {
hydrate: function( person ) {
this.setFirstname( person.firstname );
this.setLastname( person.lastname );
}
};
var john = new Person( {
firstname: "John",
lastname: "Doe"
} );