1)第一頁是有的克萊德路寶的答案:
var f = new foo();
f.bar();
2)在consturctor
(特權)上編寫函數,每個實例將創建一個新的函數,如果在prototype
上定義了方法,則每個實例都共享相同的prototype
的方法:
var f1 = new foo(), // instance 1
f2 = new foo(); // instance 2
f1.privileged === f2. privileged // -> false , every instance has different function
f1.bar === f2.bar // -> true, every instance share the some function
3)你可以調用bar2
在bar' by
this.bar()',這樣的代碼:
function foo() {
this.property = "I'm a property";
this.privileged = function() {
// do stuff
};
}
foo.prototype.bar = function() { // defined a method bar
alert('bar called');
this.bar2(); // call bar2
};
foo.prototype.bar2 = function() { // defined a method bar2
alert('bar2 called');
};
var f = new foo();
f.bar(); // alert 'bar called' and 'bar2 called'
f.bar2(); // alert 'bar2 called'
的的jsfiddle是優秀的!我讀了你的答案,並認爲「是的,有道理」。開始思考「但是如果......」和jsFiddle讓我全面測試。優秀。 – JonWells