這只是其中的原型適合:
function AB()
{};//empty object
AB.prototype.function1 = function()
{
var self = this;//doesn't have access to self, but `this` will point to either A or B
//do stuff
};
var A = function()
{
var self = this;//constructor
}
var B = function()
{
var self = this;//constructor
}
A.prototype = new AB;
A.prototype.constructor = A;
B.prototype = new AB;
B.prototype.constructor = B;
//marginally shorter:
A.prototype = B.prototype = new AB;
A.prototype.constructor = A;
B.prototype.constructor = B;
//instances:
var foo = new A();
var bar = new B();
console.log(foo.function1 === bar.function1);//logs true
話雖如此,我個人比較喜歡來定義我的構造定期:
function A()
{
var self = this;
}
foo = new A();
console.log(Object.getPrototypeOf(foo).constructor.name);//logs A
而你的代碼分配一個匿名函數轉換爲變量,這意味着構造函數沒有名稱:
foo = new A();
console.log(Object.getPrototypeOf(foo).constructor.name);//logs ''
這不是一個交易大,但只是讓你知道...
參考從全球的方法(或任何其他)範圍:
var virtualNewFunction = new A();//create object
virtualNewFunction = virtualNewFunction.function1;//virtualNewFunction now references function1
virtualNewFunction();
關閉將是可訪問(暴露),但仍然,但非常小心this
:
A = function()
{
var self = this;
this.function1 = function()
{
console.log(this);
console.log(self);
};
}
foo = new A();
foo.function1();//logs A twice
foo = foo.function1
foo();//logs this -> window! self => A
的另一種可能性是「借用」功能:
A = function()
{
var self = this;
this.function1 = function()
{
console.log(this);
console.log(self);
};
}
B = function()
{//no method
var self = this;
}
foo = new A();
bar = new B();
foo.function1.apply(bar,[]);//call as though function1 was method of B
再次,要注意:在這種情況下this
日誌B
,但self
仍然引用A
!你可以建立在某些「安全網」:
this.function1 = function()
{
self = this !== window && this !== self ? this : self;//redefine self to current caller object, unless it's window
console.log(this);
console.log(self);
};
但說實話,那你最好reading up on the this operator把握這一切引用弄虛作假。這不是那一旦你得到基礎知識就很難。另外,還要檢查call和apply方法,詳細瞭解如何「共享/借用」方法
我編輯了關於function1/function2的問題,可以請看一下嗎? – Vimvq1987
不完全確定你的意思...我會編輯我的答案,以顯示更多你可以做的事情: –
我的意思是function1和function2使用傳遞給A和B的變量 – Vimvq1987