JavaScript에서 동일한 객체의 메소드 내부에서 객체 값에 액세스하는 방법은 무엇입니까?

StackOverflow https://stackoverflow.com/questions/1822258

문제

프로토 타입을 사용하여 객체 객체 내부에 Tobool () "메소드"를 추가하려고합니다.

Object.prototype.toBool = function ()
{
 switch(this.toLowerCase())
 {
  case "true": case "yes": case "1": return true;
  case "false": case "no": case "0": case null: return false;
  default: return Boolean(string);
 }
}

var intAmount = 1;
if(intAmount.toBool()) 

하지만 동일한 개체 방법 내부에서 객체의 값에 액세스하려는 문제가 있습니다. this.toLowerCase()

어떻게해야합니까?

도움이 되었습니까?

해결책

tolowercase ()는 문자열의 메소드이지만 숫자는 아니기 때문에 코드가 작동하지 않습니다. 따라서 숫자 1에서 TolowerCase ()를 호출하려고하면 작동하지 않습니다. 솔루션은 숫자를 먼저 문자열로 변환하는 것입니다.

Object.prototype.toBool = function ()
{
 switch(String(this).toLowerCase())
 {
  case "true": case "yes": case "1": return true;
  case "false": case "no": case "0": case null: return false;
  default: return Boolean(string);
 }
}
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top