初学者JavaScript:使用JavaScript中的JSON和对象 [英] Beginner JavaScript: Working with JSON and Objects in JavaScript

查看:57
本文介绍了初学者JavaScript:使用JavaScript中的JSON和对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我将一些JSON返回给浏览器,就像这个产品一样:

I have some JSON returned to the browser like this "product":

{ "Title": "School Bag", "Image": "/images/school-bag.jpg" }

我想要这些数据是一个产品对象,所以我可以使用原型方法,如 toHTMLImage(),返回产品的HTML图像表示:

I want this data to be a "Product" object so I can use prototype methods like a toHTMLImage() that returns a HTML image representation of the product:

function Product() { }
Product.prototype.toHTMLImage = function() { //Returns something like <img src="<Image>" alt="<Title>" /> }

如何将我的JSON结果转换为产品对象,以便我可以使用 toHTMLImage

How do I convert my JSON results into a Product object so that I can use toHTMLImage?

推荐答案

简单,如果我得到它,

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

这篇关于初学者JavaScript:使用JavaScript中的JSON和对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆