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

OOP Javascript - Accessing a privileged method from public method via another public method

本文关键字:方法 访问特权 另一个 Javascript- OOP      更新时间:2023-09-26
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'

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

Person.prototype.scream = function () {
  new this.WhatToScream().screamAge();
}
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 () { ... },
    }
}