我有一些JSON返回到浏览器,就像这个"产品":
{ "Title": "School Bag", "Image": "/images/school-bag.jpg" }
Run Code Online (Sandbox Code Playgroud)
我希望这些数据是一个"产品"对象,所以我可以使用原型方法,如toHTMLImage()返回产品的HTML图像表示:
function Product() { }
Product.prototype.toHTMLImage = function() { //Returns something like <img src="<Image>" alt="<Title>" /> }
Run Code Online (Sandbox Code Playgroud)
如何将我的JSON结果转换为Product对象以便我可以使用toHTMLImage?
Jos*_*eal 19
简单,如果我得到它,
var json = { "Title": "School Bag", "Image": "/images/school-bag.jpg" }
function Product(json) {
this.img = document.createElement('img');
this.img.alt = json.Title;
this.img.src = json.Image;
this.toHTMLImage = function() {
return this.img;
}
}
var obj = new Product(json); // this is your object =D
Run Code Online (Sandbox Code Playgroud)