2012-10-26 3 views
0

JavaScript로 객체를 만드는 데 사용하는 Product라는 함수를 만들었습니다. 이제는 setProduct라는 함수를 사용하여 데이터베이스 (websql)에서 데이터를 가져 와서이 데이터를 현재 객체의 데이터베이스에서 모두 설정합니다. 내 코드는 다음과 같습니다.내부 변수에서 객체 변수가 변경되지 않습니다

function Product(nr, name, description, brand, category, price, tags, color, seccolor, image, sizes, db) { 
    this.nr    = nr; 
    this.name   = name; 
    this.description = description; 
    this.brand   = brand; 
    this.category  = category; 
    this.price   = price; 
    this.tags   = tags; 
    this.color   = color; 
    this.seccolor  = color; 
    this.image   = image; 
    this.sizes   = sizes; 
    this.db    = db; 

     Product.prototype.setProduct = function(id, cb) { 
     var self = this; 
     var query = "SELECT * from products WHERE id='"+id+"';" 
     var res; 
     this.db.exec(query, function(results) { 
      res = results.rows.item(0); 
      self.nr    = res.prod_nr; 
      self.description = res.prod_description; 
      self.brand   = res.prod_brand; 
      self.category  = res.prod_category; 
      self.price   = res.prod_price; 
      self.tags   = res.prod_tags; 
      self.color   = res.prod_color; 
      self.seccolor  = res.prod_sec_color; 
      self.image   = res.prod_image; 
      self.sizes   = res.available_sizes; 
      self.name   = res.prod_name; 
      cb(true); 
     }); 
    }; 
} 

this.db = 내 데이터베이스 개체입니다. setProduct는 해당 객체에서 exec 함수를 호출합니다. 이 코드는 다음과 같습니다.

Database.prototype.exec = function(query, cb) { 
     this.db.transaction(function(tx) { 
      tx.executeSql(query, [], function(tx, results) { 



       if (typeof(cb) == 'function') { 

         cb(results); 
        } 
       }); 
      }); 
    } 

여러 console.log를 사용하여 데이터가 손실 된 곳을 확인하려고했지만 어떻게 든 찾을 수 없습니다. 그것이 잘못되면 그 다음에

그리고는 다음과 같습니다

$("div#home").off('click').on('click','li', function() { 
      var product = prod; 
      var prod_id = $(this).attr("id"); 
      prod.setProduct(prod_id, function(a) { 
       if (a) { 
        console.log(prod.name); // console.log gives undefined 
       } 
      }); 
     }); 
} 
+4

사용 디버거를 사용하는 것을 잊었다. 추신 : ** 매우 ** 이상한 ** 생성자에서 프로토 타입 함수를 정의하는 것입니다. – zerkms

+0

@zerkms 어떤 디버거를 의미합니까? 팁 주셔서 감사합니다. 예를 들어 –

+0

과 같은 프로토 타입 함수를 넣을 것입니다. google chrome 개발자 도구 js debugger PS :'console.log'가 거짓말 할 수있는 기사는 다음과 같습니다. http://felix-kling.de/blog/2011/08/18/inspecting-variables-in-javascript-conoles/ – zerkms

답변

0

내 해결책을 발견! `) ( 나는 innerscope에 사용할 새로운 변수로 현재 개체를 추가했지만 내가 대신 CONSOLE.LOG`의 그것을

$("div#home").off('click').on('click','li', function() { 
      var product = prod; // FOR THE INNER SCOPE 
      var prod_id = $(this).attr("id"); 
      prod.setProduct(prod_id, function(a) { 
       if (a) { 
        console.log(prod.name); // prod.name has to be product.name, as defined above 
        console.log(product.name); // WORKS! 

       } 
      }); 
     }); 
} 
관련 문제