Computer >> कंप्यूटर ट्यूटोरियल >  >> प्रोग्रामिंग >> JavaScript

एक जावास्क्रिप्ट कंस्ट्रक्टर के लिए एक संपत्ति, विधि कैसे जोड़ें?


जावास्क्रिप्ट कंस्ट्रक्टर में प्रॉपर्टी, विधि जोड़ने के लिए निम्नलिखित कोड है -

उदाहरण

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Document</title>
<style>
   body {
      font-family: "Segoe UI", Tahoma, Geneva, Verdana, sans-serif;
   }
   .result {
      font-size: 20px;
      font-weight: 500;
      }
</style>
</head>
<body>
<h1>Add property,method to javaScript constructor</h1>
<div style="color: green;" class="result"></div>
<button class="Btn">CLICK HERE</button>
<h3>Click on the above button to add property, method to constructor</h3>
<script>
   let resEle = document.querySelector(".result");
   function Human(firstName,lastName){
      this.firstName = firstName;
      this.lastName = lastName;
   }  
   let obj = new Human('Rohan','Sharma');
   document.querySelector(".Btn").addEventListener("click", () => {
      Human.prototype.welcome = function(){
         return 'Welcome '+this.firstName + ' ' + this.lastName;
      }
      Human.prototype.age = 22;
      resEle.innerHTML = 'Adding property to constructor : age <br>' + obj.age + '<br>';
      resEle.innerHTML += 'Adding function to constructor : welcome() <br>' +
      obj.welcome() + '<br>';
   });
</script>
</body>
</html>

आउटपुट

उपरोक्त कोड निम्न आउटपुट उत्पन्न करेगा -

एक जावास्क्रिप्ट कंस्ट्रक्टर के लिए एक संपत्ति, विधि कैसे जोड़ें?

'यहां क्लिक करें' बटन पर क्लिक करने पर -

एक जावास्क्रिप्ट कंस्ट्रक्टर के लिए एक संपत्ति, विधि कैसे जोड़ें?


  1. जावास्क्रिप्ट बूलियन कंस्ट्रक्टर संपत्ति जावास्क्रिप्ट बूलियन कंस्ट्रक्टर संपत्ति

    बूलियन कंस्ट्रक्टर प्रॉपर्टी बूलियन प्रोटोटाइप बनाने वाले कंस्ट्रक्टर फ़ंक्शन को लौटाती है - JavaScript बूलियन कंस्ट्रक्टर प्रॉपर्टी के लिए कोड निम्नलिखित है - उदाहरण <!DOCTYPE html> <html> <head> <style>    body {       font-family: "Segoe UI&q

  1. जावास्क्रिप्ट दिनांक निर्माता संपत्ति जावास्क्रिप्ट दिनांक निर्माता संपत्ति

    JavaScript दिनांक कंस्ट्रक्टर प्रॉपर्टी दिनांक के कंस्ट्रक्टर फ़ंक्शन को लौटाती है। जावास्क्रिप्ट दिनांक निर्माता संपत्ति के लिए कोड निम्नलिखित है - उदाहरण <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8" /> <meta name="viewport"

  1. जावास्क्रिप्ट में लूप में देरी कैसे जोड़ें? जावास्क्रिप्ट में लूप में देरी कैसे जोड़ें?

    लूप में देरी जोड़ने के लिए, जावास्क्रिप्ट में सेटटाइमआउट () विधि का उपयोग करें। लूप में विलंब जोड़ने के लिए कोड निम्नलिखित है - उदाहरण <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8" /> <meta name="viewport" content="width=d