Create an object-oriented security model of the object

var Book = function(title,time,type){
    this.title = title;
    this.time = time;
    this.type = type;
}

var book = Book('JavaScrity','2019','js')

The above example you might think this book should be a variable instance of it.

We use the code to test what he is

console.log(book); //undefined

It is actually a undefined! Why is this?

We look at this test code

console.log(window.title);   //JavaScript
console.log(window.time);  //2019
console.log(window.type);  //js

  Obviously create a Book object, and add a title, time, type these three attributes, why would add to the window to go above it? And book this variable is undefined. Because the object is instantiated when there is no write new but why is it so it?

  The role of new keywords can be seen as an assignment to keep current this object, but with no new cases, it will perform this function directly, and this function is executed in the global scope, so in the global scope this points to the current object of nature is global. and our global variable page is the window, so the added attribute will naturally be added to the top of the window ... and the final action of our book variable is to get this Book class (function) of the results, since it has the function return statement, the Book class naturally not tell the results book of variables, and so is undefined (undefined).

In order to avoid such a situation, we had a safe mode called the stuff:

var Book = function (title, Time, type) {
     // determines whether execution of this object is the current 
    IF ( this  the instanceof Book) {
         this .title = title;
         this .time = Time;
         this .Type = type; 
    } the else {
         return  new new Book (title, Time, type); 
    } 
} 

var Book = Book ( 'the JavaScript', '2019', 'JS')

This time test is:

console.log(book);  //Book
console.log(book.title);  //JavaScript
console.log(book.time);  //2019
console.log(book.type);  //js
console.log(window.title);  //undefined
console.log(window.time);  //undefined
console.log(window.type);  //undefined
 

 

Guess you like

Origin www.cnblogs.com/evilr/p/11572012.html