考虑这段代码:
var obj = {
width : 10,
height : 10,
img : new Image(),
img.src : "assets/img.png" // this is where I get an error
};
我在img.src
上收到错误。我之后是否必须设置src或是否有解决方法?
答案 0 :(得分:2)
是的,您必须将其设置为向后,除非您想将img
初始化包裹在IIFE中:
var obj = {
width: 10,
height: 10,
img: (function() {
var img = new Image();
img.src = "http://i.stack.imgur.com/KUvWS.jpg";
return img;
})()
};
console.log("img src: %o", obj.img.src);

...或使用Object.assign()
:
var obj = {
width: 10,
height: 10,
img: Object.assign(new Image, {
src: "http://i.stack.imgur.com/KUvWS.jpg"
})
};
console.log("img src: %o", obj.img.src);