with 키워드는 개체의 속성이나 메서드를 참조하기 위한 일종의 약어로 사용됩니다.
with에 대한 인수로 지정된 개체는 다음 블록 기간 동안 기본 개체가 됩니다. 개체의 속성과 메서드는 개체의 이름을 지정하지 않고 사용할 수 있습니다.
구문
with 객체의 구문은 다음과 같습니다 -
with (object){
properties used without the object name and dot
} 예시
다음 코드를 학습하여 키워드로 구현하는 방법을 배울 수 있습니다 −
실시간 데모
<html>
<head>
<title>User-defined objects</title>
<script>
// Define a function which will work as a method
function addPrice(amount){
with(this){
price = amount;
}
}
function book(title, author){
this.title = title;
this.author = author;
this.price = 0;
this.addPrice = addPrice; // Assign that method as property.
}
</script>
</head>
<body>
<script type="text/javascript">
var myBook = new book("Python", "Tutorialspoint");
myBook.addPrice(100);
document.write("Book title is : " + myBook.title + "<br>");
document.write("Book author is : " + myBook.author + "<br>");
document.write("Book price is : " + myBook.price + "<br>");
</script>
</body>
</html> 출력
Book title is : Python Book author is : Tutorialspoint Book price is : 100