var Person = function (name, age) {
this.name = name;
this.age = age;
}
Person.prototype.scream = function () {
this.WhatToScream.screamAge();
}
Person.prototype.WhatToScream = function () {
this.screamAge = function () {
alert('I AM ' + this.age + ' YEARS OLD!!!');
}
this.screamName = function () {
alert('MY NAME IS ' + this.name + '!!!')
}
}
var man = new Person('Berna', 21);
man.scream();
// This code raises:
// Uncaught TypeError: Object WhatToScream has no method 'screamAge'
質問する
75 次
2 に答える
2
元のコードに近い再定義を次に示します。
Person.prototype.scream = function () {
new this.WhatToScream().screamAge();
}
于 2013-06-22T07:24:05.507 に答える
1
var Person = function (name, age) {
this.name = name;
this.age = age;
}
Person.prototype.scream = function () {
// get function screamAge from container WhatToScream,
// which is available in the instance of the object,
// because it was defined in the prototype
// and then call it with thisArg being current this,
// which is pointing to current container,
// * which at runtime is man
this.WhatToScream.screamAge.call(this);
}
Person.prototype.WhatToScream = {
screamAge: function () {
alert('I AM ' + this.age + ' YEARS OLD!!!');
},
screamName: function () {
alert('MY NAME IS ' + this.name + '!!!')
}
}
var man = new Person('Berna', 21);
man.scream();
関数として保持したい場合はWhatToScream
、それを呼び出して、返されるオブジェクトを使用する必要があります。
Person.prototype.scream = function () {
this.WhatToScream().screamAge.call(this);
}
Person.prototype.WhatToScream = function () {
return {
screamAge: function () { ... },
screamName: function () { ... },
}
}
于 2013-06-22T07:07:57.190 に答える