![](/img/trans.png)
[英]How to expose jQuery native / local scope to variables to extend object methods
[英]how to expose public methods of member variables in JS
我上课了
function A()
{
var that = this;
var b = new B();
this.setBSize = function(newSize)
{
b.setSize(newSize);
}
};
function B()
{
var that = this;
this.setSize = function(newSize)
{
...
}
}
a = new A();
a.setBSize(5);
如何避免编写setBSize方法? 如何自动公开b的公共方法? 我想这样打电话
a.setSize(5);
我还需要一个new B();
的引用new B();
哪个是A()
里面A()
b A()
你总是可以设置的原型A
到B
,如果你想继承所有方法B
function A() {
var that = this;
};
function B() {
var that = this;
this.setSize = function (newSize) {
console.log(newSize); // 5
}
}
A.prototype = new B();
a = new A();
a.setSize(5);
在jQuery
: $.extend(that, new B());
在angular
: angular.extend(that, new B());
function A()
{
var that = this;
$.extend(that, new B());
};
function B()
{
var that = this;
this.setSize = function(newSize)
{
...
}
}
a = new A();
a.setSize(5);
如果你想在B()
类中使用任何private
变量,则将它们定义为var someVar
,将所有公共(可that.somePublicVar
)变量定义为that.somePublicVar
你可以使用call
方法:
function A() {
var that = this;
B.call(this);
};
function B() {
var that = this;
this.setSize = function (newSize) {
this.size = newSize;
}
}
var a = new A();
a.setSize(5);
基本上你调用B
在上下文A
,什么情况是,所有的自身属性B
实例都将被分配到this
这是A
实例。 这种模式称为构造函数或方法借用。
你应该利用原型。
创建一个在所有类(对象)之间共享函数的构造函数:
var myConstructor = function(newSize){
this.setSize = function(newSize)
{
...
}
}
现在你做instanciation:
var a = new myConstructor(someSize);
var b = new myConstrucotr(someSize);
现在有了这个改变, a.setSize()
和b.setSize()
使用prototype继承方法setSize
并丢弃所有this
和that
代码。
function B() {
};
function A() {
B.call(this);
};
B.prototype.setSize = function(newSize) {
console.log(newSize);
}
A.prototype = Object.create(B.prototype);
A.prototype.constructor = A;
var a = new A();
a.setSize(5); // 5
console.log(a instanceof A);// true
console.log(a instanceof B);// true
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.