[英]How to copy objects inside constructor in javascript
我想創建一個自定義圖像構造函數:
var image1 = new imgConstructor("picture.png", 100, 50);
我試過了:
var imgConstructor = function(src, width, height) {
this = new Image(width, height);
this.src = src;
}
但是this = new Image()
無效。
我知道我可以用工廠功能來做到這一點:
var imgConstructor = function(src, width, height) {
var img = new Image(width, height);
img.src = src;
return img;
}
var image1 = imgConstructor("picture.png", 100, 50);
但我想用構造函數,使用“new” 。 有任何想法嗎?
但我想用構造函數,使用
new
。 有任何想法嗎?
不,那是不可能的。 畢竟你將無法繼承Image
。 如果您需要使用自己的方法“實例”,最好創建一個包裝器對象(比如在this.img = new Image(…)
執行this.img = new Image(…)
)。
使用工廠功能完全沒問題,這似乎是合適的。 如果由於某種原因想要使用new
,可以在工廠函數中使用new
,它仍然可以工作(雖然產生Image
,而不是imgConstructor
的實例)。
基本說明:
var a = new Image();
console.log(a.constructor); // Should be function Image() { [native code] }
// OUTPUT: function HTMLImageElement() { [native code] }
var b = new HTMLImageElement();
// Uncaught TypeError: Illegal constructor
所以,你的解決方案是正確的。
編輯:來自@ user86745458的解決方案正在運行,但正如@Bergi所說:
當有人調用新的imgConstructor時,通常會期望結果是imgConstructor的一個實例。 它並不總是,因為構造函數顯式返回一個可能不同的對象。
嘗試應用舊解決方案(來自@ user86745458)並檢查:
new imgConstructor() instanceof imgConstructor
// OUTPUT: false
imgConstructor() instanceof imgConstructor
// OUTPUT: false
imgConstructor() instanceof Image
// OUTPUT: true
嘗試添加這樣的東西
var imgConstructor = function(src, width, height) {
var img = this;
img = new Image(width, height);
img.onload = function(){
// image has been loaded
};
img.src = src;
return img;
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.