OOP Javascript-通过另一个公共方法从公共方法访问特权方法
OOP Javascript - Accessing a privileged method from public method via another public method
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 () { ... },
}
}
相关文章:
- 如何从对象的原型方法访问JavaScript对象属性
- 使构造函数参数具有ES6类方法的特权
- 如何从其他方法访问Angular.js$scope
- 从同一控制器 Angularjs 中的另一种方法访问$scope变量
- 是否可以从 javascript 中的原型方法访问私有类属性
- 从子方法访问父对象
- 从 CoffeeScript 中类的属性中的方法访问属性的属性
- 使JavaScript私有方法可供其公共方法访问
- RequireJS, Pub/Sub.如果没有糟糕的解决方法,我无法从其自己的方法访问视图实例
- Javascript 从父级中定义的继承类方法访问类变量
- 实例化后可从方法访问的 Javascript 局部变量
- 私有变量通过javascript中的私有方法访问
- 如何在javascript中的同一对象中使用公共方法访问私有变量
- 无法通过javascript中的特权方法访问私有方法
- 从公共方法访问私有对象变量
- 无法通过公共方法访问javascript私有成员
- 我使用什么JavaScript模式从原型方法访问私有方法
- 如何通过ASP.NET WebForm上的jQuery$.get()方法访问URL
- OOP Javascript-通过另一个公共方法从公共方法访问特权方法
- 从子方法访问父属性