[英]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.