OOP Javascript - 通过另一个公共方法从公共方法访问特权方法

时间:2013-06-22 06:53:23

标签: javascript oop

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'

2 个答案:

答案 0 :(得分:2)

这是一个更接近原始代码的重新定义:

Person.prototype.scream = function () {
  new this.WhatToScream().screamAge();
}

答案 1 :(得分: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 () { ... },
    }
}