Bằng tất cả các nhận xét khác, tôi đã tạo một ví dụ phù hợp với tôi. Vì tôi không sử dụng nguyên mẫu một cách rõ ràng nên tôi hy vọng tôi không bỏ lỡ một điểm quan trọng nào.
// variable for tracking instantiations and checking the uniqueness of the objects
var instances = 0;
var Generic = function() {
this.instanceId = ++instances;
this.toString = function() {return 'Generic [iid='+ this.instanceId +']'};
console.log('constructor-invoke: Generic ('+ this.instanceId +')');
};
var SpecificName = function(inName) {
Generic.call(this);
this.getName = function() { return inName; };
var superToString = this.toString.bind(this); // binds the inner function 'this' to this SpecificName instance
this.toString = function() {
return 'SpecificName [iid='+ this.instanceId +', name='+ this.getName() +', super.toString='+ superToString() +']'
}
console.log('constructor-invoke: SpecificName ('+ this.instanceId +')');
};
var SpecificNames = function(inFirstName, inLastName) {
SpecificName.call(this, inLastName +', '+ inFirstName);
var superToString = this.toString.bind(this);
this.toString = function() {
return 'SpecificNames [iid='+ this.instanceId +', name='+ this.getName() +', super.toString='+ superToString() +']'
}
console.log('constructor-invoke: SpecificNames ('+ this.instanceId +')');
};
var g = new Generic();
var sn = new SpecificName('Run Forest Run');
var sns = new SpecificNames('Forest','Gump');
console.log('g: '+ g.toString());
console.log('sn: '+ sn.toString());
console.log('sns: '+ sns.toString());
dẫn đến kết quả này:
constructor-invoke: Generic (1)
constructor-invoke: Generic (2)
constructor-invoke: SpecificName (2)
constructor-invoke: Generic (3)
constructor-invoke: SpecificName (3)
constructor-invoke: SpecificNames (3)
g: Generic [iid=1]
sn: SpecificName [iid=2, name=Run Forest Run, super.toString=Generic [iid=2]]
sns: SpecificNames [iid=3, name=Gump, Forest, super.toString=SpecificName [iid=3, name=Gump, Forest, super.toString=Generic [iid=3]]]
Nguồn
2015-08-11 12:21:15
@CMS Đối với phần thứ hai 'if (arguments.length == 0) trả về;', có cách nào để xử lý các hàm tạo trong đó các đối số KHÔNG được yêu cầu không? Trong tình huống đó, tôi có bị buộc phải gọi cho nhà xây dựng không? –
Tôi đã thử nhiều phương pháp khác nhau ('Object.create',' Person.prototype', các chức năng tạm thời ...) nhưng tất cả chúng đều thất bại hoặc có lỗi (các thuộc tính không xác định, các thuộc tính bị che khuất, v.v.). Cảm ơn câu trả lời này, cuối cùng câu trả lời đó thực sự hiệu quả! – TheBronx