0
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'
4

2 回答 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 回答