2015-06-17 83 views
1
function Foo (name) { 
    this.name = name; 
} 

Foo.prototype.bar = { 
    n: function() { 
     // How to get here after initializing the object foo? 
    } 
}; 

var a = new Foo('John'); 
console.log(a.bar.n()) 

如何在初始化對象foo後進入此處?初始化後獲取原型對象的屬性

+0

這種模式通常不會被利用,因爲您需要跳過一些箍環才能使其工作。是不是真正的慣用JavaScript。 –

+0

我知道,但仍然.. – Aleksandr

+1

你是什麼意思的「如何到達這裏?」 – rsp

回答

1

爲了給你一個什麼樣的需要得到那個工作的想法,這裏有一個演示:

function Foo (name) { 
 
    this.name = name; 
 
} 
 

 
Object.defineProperty(Foo.prototype, "bar", { 
 
    get: function() { 
 
     var that = this; 
 
     return { 
 
      n: function() { 
 
       return that.name 
 
      } 
 
     } 
 
    } 
 
}); 
 

 
var a = new Foo('John'); 
 
document.querySelector("pre").textContent = a.bar.n();
<pre></pre>

會發生什麼事是,bar財產變成創建並返回一個getter具有關閉this值的新函數的新對象。

這意味着每次訪問該屬性時都會產生一些開銷。這種技術是必要的,因爲當訪問屬性時,對象和屬性之間的唯一關係就會發生。之後,這種關係被遺忘了。

因此,原型遺傳的幾乎所有好處都丟失了。這應該被認爲是IMO僅用於學術目的。

+0

非常好!謝謝! – Aleksandr

+1

不客氣。 –