Home Web Front-end JS Tutorial A daily javascript learning summary (object-oriented programming)_javascript skills

A daily javascript learning summary (object-oriented programming)_javascript skills

May 16, 2016 pm 03:31 PM
Object-Oriented Programming

1. Object-oriented factory method

 function createPerson(name, age, job){
   var o = new Object();
   o.name = name;
   o.age = age;
   o.job = job;
   o.sayName = function(){
    alert(this.name);
   }; 
   return o;
  }
  
  var person1 = createPerson("Nicholas", 29, "Software Engineer");
  var person2 = createPerson("Greg", 27, "Doctor");
  
  person1.sayName(); //"Nicholas"
  person2.sayName(); //"Greg"
Copy after login

The disadvantage of the factory model method is that it will generate a lot of duplicate code!

2. Constructor pattern creates objects

 function Person(name, age, job){
   this.name = name;
   this.age = age;
   this.job = job;
   this.sayName = function(){
    alert(this.name);
   }; 
  }
  
  var person1 = new Person("Nicholas", 29, "Software Engineer");
  var person2 = new Person("Greg", 27, "Doctor");
  
  person1.sayName(); //"Nicholas"
  person2.sayName(); //"Greg"
  
  alert(person1 instanceof Object); //true
  alert(person1 instanceof Person); //true
  alert(person2 instanceof Object); //true
  alert(person2 instanceof Person); //true
  
  alert(person1.constructor == Person); //true
  alert(person2.constructor == Person); //true
  
  alert(person1.sayName == person2.sayName); //false  
Copy after login

Using the new keyword to create an object will go through the following four processes

  • 1. Create a new object
  • 2. Assign the scope of the constructor to a new object (so this points to this new object)
  • 3. Method to execute the constructor (assign a value to this new object)
  • 4. Return new object

3. Use the constructor as a function

 function Person(name, age, job){
   this.name = name;
   this.age = age;
   this.job = job;
   this.sayName = function(){
    alert(this.name);
   };
  }
  
  var person = new Person("Nicholas", 29, "Software Engineer");
  person.sayName(); //"Nicholas"
  
  Person("Greg", 27, "Doctor"); //adds to window
  window.sayName(); //"Greg"
  
  var o = new Object();
  Person.call(o, "Kristen", 25, "Nurse");
  o.sayName(); //"Kristen"
Copy after login

When used as a function, the constructor is no different from an ordinary function. It is just a method added under the window object. Since the object created by the constructor actually creates a new object, the two are essentially different and separated, and their methods are still different!

4. Use common methods to solve inconsistent problems globally

 function Person(name, age, job){
   this.name = name;
   this.age = age;
   this.job = job;
   this.sayName = sayName;
  }
  
  function sayName(){
   alert(this.name);
  }
  
  var person1 = new Person("Nicholas", 29, "Software Engineer");
  var person2 = new Person("Greg", 27, "Doctor");
  
  person1.sayName(); //"Nicholas"
  person2.sayName(); //"Greg"
  
  alert(person1 instanceof Object); //true
  alert(person1 instanceof Person); //true
  alert(person2 instanceof Object); //true
  alert(person2 instanceof Person); //true
  
  alert(person1.constructor == Person); //true
  alert(person2.constructor == Person); //true
  
  alert(person1.sayName == person2.sayName); //true  
Copy after login

Although the above method solves the same problem, the defined global method itself belongs to the window, so there is no separation between local and global! So this method is rarely used! Not recommended either.

5. Prototype mode

Any function we create has a prototype object. This attribute is a pointer, which points to an object, and the function of this object is to have methods that can be shared by all instances of a specific type!

 function Person(){
  }
  
  Person.prototype.name = "Nicholas";
  Person.prototype.age = 29;
  Person.prototype.job = "Software Engineer";
  Person.prototype.sayName = function(){
   alert(this.name);
  };
  
  var person1 = new Person();
  person1.sayName(); //"Nicholas"
  
  var person2 = new Person();
  person2.sayName(); //"Nicholas"
  
  alert(person1.sayName == person2.sayName); //true
  
  alert(Person.prototype.isPrototypeOf(person1)); //true
  alert(Person.prototype.isPrototypeOf(person2)); //true
  
  //only works if Object.getPrototypeOf() is available
  if (Object.getPrototypeOf){
   alert(Object.getPrototypeOf(person1) == Person.prototype); //true
   alert(Object.getPrototypeOf(person1).name); //"Nicholas"
  }
Copy after login

Understanding prototypes

Whenever a function is created, a prototype property is created, which points to the prototype object of the function. By default, the prototype object will contain a constructor (constructor attribute), which contains a pointer to the function where the prototype attribute is located!

The order of attribute reading

Every time the code reads the properties of an object, it will perform a search. The target is the property with the given name. The search starts from the instance of the object itself. If there is one, it will be returned. If not, it will continue to search for the object. Prototype chain until the outermost layer of the prototype chain is searched!

 function Person(){
  }
  
  Person.prototype.name = "Nicholas";
  Person.prototype.age = 29;
  Person.prototype.job = "Software Engineer";
  Person.prototype.sayName = function(){
   alert(this.name);
  };
  
  var person1 = new Person();
  var person2 = new Person();
  
  person1.name = "Greg";
  alert(person1.name); //"Greg" 来自实例
  alert(person2.name); //"Nicholas" 来自原型
Copy after login

If the instance attribute of this element is deleted

function Person(){
  }
  
  Person.prototype.name = "Nicholas";
  Person.prototype.age = 29;
  Person.prototype.job = "Software Engineer";
  Person.prototype.sayName = function(){
   alert(this.name);
  };
  
  var person1 = new Person();
  var person2 = new Person();
  
  person1.name = "Greg";
  alert(person1.name); //"Greg" ?from instance
  alert(person2.name); //"Nicholas" ?from prototype
  
  delete person1.name;
  alert(person1.name); //"Nicholas" - from the prototype
Copy after login

6. hasOwnProperty method

This method can detect whether a property exists in the instance or in the prototype! hasOwnProperty is inherited from Object and will return true as long as the given property exists in the object instance.

 function Person(){
    }
    
    Person.prototype.name = "Nicholas";
    Person.prototype.age = 29;
    Person.prototype.job = "Software Engineer";
    Person.prototype.sayName = function(){
      alert(this.name);
    };
    
    var person1 = new Person();
    var person2 = new Person();
    
    alert(person1.hasOwnProperty("name")); //false
    alert("name" in person1); //true
    
    person1.name = "Greg";
    alert(person1.name);  //"Greg" ?from instance
    alert(person1.hasOwnProperty("name")); //true
    alert("name" in person1); //true
    
    alert(person2.name);  //"Nicholas" ?from prototype
    alert(person2.hasOwnProperty("name")); //false
    alert("name" in person2); //true
    
    delete person1.name;
    alert(person1.name);  //"Nicholas" - from the prototype
    alert(person1.hasOwnProperty("name")); //false
    alert("name" in person1); //true
Copy after login

7. Object.keys() enumerable property method

This method receives an object as a parameter and returns a string array containing all enumerable properties

 function Person(){
    }
    
    Person.prototype.name = "Nicholas";
    Person.prototype.age = 29;
    Person.prototype.job = "Software Engineer";
    Person.prototype.sayName = function(){
      alert(this.name);
    };
    
    var keys = Object.keys(Person.prototype);
    alert(keys);  //"name,age,job,sayName"
如果想得到所有实例的属性,无论它是否可以枚举都可以使用这个方法来获取
 function Person(){
    }
    
    Person.prototype.name = "Nicholas";
    Person.prototype.age = 29;
    Person.prototype.job = "Software Engineer";
    Person.prototype.sayName = function(){
      alert(this.name);
    };
    
    var keys = Object.getOwnPropertyNames(Person.prototype);
    alert(keys);  //"constructor,name,age,job,sayName"
Copy after login

This method is only supported by higher version browsers

8. Simple prototype writing method

 function Person(){
    }
    
    Person.prototype = {
      name : "Nicholas",
      age : 29,
      job: "Software Engineer",
      sayName : function () {
        alert(this.name);
      }
    };

    var friend = new Person();
    
    alert(friend instanceof Object); //true
    alert(friend instanceof Person); //true
    alert(friend.constructor == Person); //false
    alert(friend.constructor == Object); //true

Copy after login

Rewriting the prototype is equivalent to overwriting the default prototype method, then the same construction method will also be rewritten, and the rewritten construction method points to the Object object! Instead of the original object Person

If you still want to point to the previous constructor, you can specify it explicitly

 function Person(){
    }
    
    Person.prototype = {
      constructor : Person,
      name : "Nicholas",
      age : 29,
      job: "Software Engineer",
      sayName : function () {
        alert(this.name);
      }
    };

    var friend = new Person();
    
    alert(friend instanceof Object); //true
    alert(friend instanceof Person); //true
    alert(friend.constructor == Person); //true
    alert(friend.constructor == Object); //false

Copy after login

9. Dynamic addition of prototype methods

function Person(){
    }
    
    Person.prototype = {
      constructor: Person,
      name : "Nicholas",
      age : 29,
      job : "Software Engineer",
      sayName : function () {
        alert(this.name);
      }
    };
    
    var friend = new Person();
    
    Person.prototype.sayHi = function(){
      alert("hi");
    };
    
    friend.sayHi();  //"hi" ?works!
Copy after login

10. Prototype methods of native objects

alert(typeof Array.prototype.sort);     //"function"
    alert(typeof String.prototype.substring);  //"function"

    String.prototype.startsWith = function (text) {//修改原生对象的原型方法
      return this.indexOf(text) == 0;
    };
    
    var msg = "Hello world!";
    alert(msg.startsWith("Hello"));  //true

Copy after login

11. Create objects using a combination of constructors and prototype patterns

//构造函数模式
function Person(name, age, job){
      this.name = name;
      this.age = age;
      this.job = job;
      this.friends = ["Shelby", "Court"];
    }
    //原型模式
    Person.prototype = {
      constructor: Person,
      sayName : function () {
        alert(this.name);
      }
    };
    
    var person1 = new Person("Nicholas", 29, "Software Engineer");
    var person2 = new Person("Greg", 27, "Doctor");
    
    person1.friends.push("Van");
    
    alert(person1.friends);  //"Shelby,Court,Van"
    alert(person2.friends);  //"Shelby,Court"
    alert(person1.friends === person2.friends); //false
    alert(person1.sayName === person2.sayName); //true
Copy after login

12. Dynamic prototype mode

function Person(name, age, job){
    
      //properties
      this.name = name;
      this.age = age;
      this.job = job;
      
      //methods
      if (typeof this.sayName != "function"){
      
        Person.prototype.sayName = function(){
          alert(this.name);
        };
        
      }
    }

    var friend = new Person("Nicholas", 29, "Software Engineer");
    friend.sayName();

Copy after login

13. Parasitic constructor pattern

 function Person(name, age, job){
var o = new Object();//依赖全局对象初始化一个对象,然后再返回这个对象
o.name = name;
o.age = age;
o.job = job;
o.sayName = function(){
alert(this.name);
}; 
return o;
}

var friend = new Person("Nicholas", 29, "Software Engineer");
friend.sayName(); //"Nicholas"

function SpecialArray(){ 

//create the array
var values = new Array();

//add the values
values.push.apply(values, arguments);

//assign the method
values.toPipedString = function(){
return this.join("|");
};

//return it
return values; 
}

var colors = new SpecialArray("red", "blue", "green");
alert(colors.toPipedString()); //"red|blue|green"

alert(colors instanceof SpecialArray);

Copy after login

A little explanation for the appeal method, because it relies on the outer object to create a new object, it cannot rely on the instanceof method to determine the source of properties and methods! It actually has nothing to do with the constructor!

14. Safe constructor pattern

 function Person(name, age, job){
      var o = new Object();
      o.sayName = function(){
        alert(name);
      };  
      return o;
    }
    
    var friend = Person("Nicholas", 29, "Software Engineer");
    friend.sayName(); //"Nicholas"
Copy after login

This method does not rely on any new this keyword! If you want to access the methods and properties of an object, you can only get them through the methods that the object has defined!

15. Inheritance
Javascript implements inheritance through the prototype chain

function SuperType(){
      this.property = true;//定义一个属性
    }
    
    SuperType.prototype.getSuperValue = function(){//定义的原型方法
      return this.property;
    };
    
    function SubType(){
      this.subproperty = false;
    }
    
    //inherit from SuperType
    SubType.prototype = new SuperType();
    
    SubType.prototype.getSubValue = function (){
      return this.subproperty;
    };
    
    var instance = new SubType();
    alert(instance.getSuperValue());  //true
    
    alert(instance instanceof Object);   //true
    alert(instance instanceof SuperType);  //true
    alert(instance instanceof SubType);   //true

    alert(Object.prototype.isPrototypeOf(instance));  //true
    alert(SuperType.prototype.isPrototypeOf(instance)); //true
    alert(SubType.prototype.isPrototypeOf(instance));  //true
SubType继承SuperType的方法和属性,因此当instance可以直接调用SuperType的方法!
 function SuperType(){
      this.property = true;
    }
    
    SuperType.prototype.getSuperValue = function(){
      return this.property;
    };
    
    function SubType(){
      this.subproperty = false;
    }
    
    //inherit from SuperType
    SubType.prototype = new SuperType();
    
    //new method
    SubType.prototype.getSubValue = function (){
      return this.subproperty;
    };
    
    //override existing method
    SubType.prototype.getSuperValue = function (){
      return false;
    };
    
    var instance = new SubType();
    alert(instance.getSuperValue());  //false

Copy after login

The above example shows that the overridden prototype will overwrite the previously inherited prototype, and the final result returned is often not the expected effect

 function SuperType(){
      this.property = true;
    }
    
    SuperType.prototype.getSuperValue = function(){
      return this.property;
    };
    
    function SubType(){
      this.subproperty = false;
    }
    
    //inherit from SuperType
    SubType.prototype = new SuperType();
    
    //使用字面量添加的方法导致上面的方法失效了
    SubType.prototype = {
      getSubValue : function (){
        return this.subproperty;
      },
    
      someOtherMethod : function (){
        return false;
      }
    }; 
    
    var instance = new SubType();
    console.log(instance);
    alert(instance.getSuperValue());  //error!
Copy after login

The following example also illustrates the risks of rewriting prototypes

 function SuperType(){
      this.colors = ["red", "blue", "green"];
    }

    function SubType(){      
    }
    
    //inherit from SuperType
    SubType.prototype = new SuperType();

    var instance1 = new SubType();
    instance1.colors.push("black");
    alert(instance1.colors);  //"red,blue,green,black"
    
    var instance2 = new SubType();
    alert(instance2.colors);  //"red,blue,green,black"

Copy after login

原型共享导致两个不同的对象调用的同一个数据
16、借用构造函数来实现继承

 function SuperType(){
      this.colors = ["red", "blue", "green"];
    }

    function SubType(){ 
      //inherit from SuperType
      SuperType.call(this);
    }

    var instance1 = new SubType();
    instance1.colors.push("black");
    alert(instance1.colors);  //"red,blue,green,black"
    
    var instance2 = new SubType();
    alert(instance2.colors);  //"red,blue,green"

Copy after login

传递参数

 function SuperType(name){
      this.name = name;
    }

    function SubType(){ 
      //inherit from SuperType passing in an argument
      SuperType.call(this, "Nicholas");
      
      //instance property
      this.age = 29;
    }

    var instance = new SubType();
    alert(instance.name);  //"Nicholas";
    alert(instance.age);   //29

Copy after login

17、组合继承方式

function SuperType(name){
      this.name = name;
      this.colors = ["red", "blue", "green"];
    }
    
    SuperType.prototype.sayName = function(){
      alert(this.name);
    };

    function SubType(name, age){ 
      SuperType.call(this, name);
      
      this.age = age;
    }

Copy after login

18、原型继承

 function object(o){
      function F(){}
      F.prototype = o;
      return new F();
    }
    
    var person = {
      name: "Nicholas",
      friends: ["Shelby", "Court", "Van"]
    };
    
    var anotherPerson = object(person);
    anotherPerson.name = "Greg";
    anotherPerson.friends.push("Rob");
Copy after login

19、寄生组合式继承

 function object(o){
      function F(){}
      F.prototype = o;
      return new F();
    }
  
    function inheritPrototype(subType, superType){
      var prototype = object(superType.prototype);  //create object
      prototype.constructor = subType;        //augment object
      subType.prototype = prototype;         //assign object
    }
                
    function SuperType(name){
      this.name = name;
      this.colors = ["red", "blue", "green"];
    }
    
    SuperType.prototype.sayName = function(){
      alert(this.name);
    };

    function SubType(name, age){ 
      SuperType.call(this, name);
      
      this.age = age;
    }

    inheritPrototype(SubType, SuperType);
    
    SubType.prototype.sayAge = function(){
      alert(this.age);
    };
    
    var instance1 = new SubType("Nicholas", 29);
    instance1.colors.push("black");
    alert(instance1.colors); //"red,blue,green,black"
    instance1.sayName();   //"Nicholas";
    instance1.sayAge();    //29
    
    
    var instance2 = new SubType("Greg", 27);
    alert(instance2.colors); //"red,blue,green"
    instance2.sayName();   //"Greg";
    instance2.sayAge();    //27
Copy after login

以上就是今天的javascript学习小结,之后每天还会继续更新,希望大家继续关注。

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
2 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
2 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

PHP MVC Architecture: Building Web Applications for the Future PHP MVC Architecture: Building Web Applications for the Future Mar 03, 2024 am 09:01 AM

Introduction In today's rapidly evolving digital world, it is crucial to build robust, flexible and maintainable WEB applications. The PHPmvc architecture provides an ideal solution to achieve this goal. MVC (Model-View-Controller) is a widely used design pattern that separates various aspects of an application into independent components. The foundation of MVC architecture The core principle of MVC architecture is separation of concerns: Model: encapsulates the data and business logic of the application. View: Responsible for presenting data and handling user interaction. Controller: Coordinates the interaction between models and views, manages user requests and business logic. PHPMVC Architecture The phpMVC architecture follows the traditional MVC pattern, but also introduces language-specific features. The following is PHPMVC

'PHP Object-Oriented Programming Design Patterns: Understanding SOLID Principles and Their Applications' 'PHP Object-Oriented Programming Design Patterns: Understanding SOLID Principles and Their Applications' Feb 25, 2024 pm 09:20 PM

SOLID principles are a set of guiding principles in object-oriented programming design patterns that aim to improve the quality and maintainability of software design. Proposed by Robert C. Martin, SOLID principles include: Single Responsibility Principle (SRP): A class should be responsible for only one task, and this task should be encapsulated in the class. This can improve the maintainability and reusability of the class. classUser{private$id;private$name;private$email;publicfunction__construct($id,$nam

Application of golang functions in high concurrency scenarios in object-oriented programming Application of golang functions in high concurrency scenarios in object-oriented programming Apr 30, 2024 pm 01:33 PM

In high-concurrency scenarios of object-oriented programming, functions are widely used in the Go language: Functions as methods: Functions can be attached to structures to implement object-oriented programming, conveniently operating structure data and providing specific functions. Functions as concurrent execution bodies: Functions can be used as goroutine execution bodies to implement concurrent task execution and improve program efficiency. Function as callback: Functions can be passed as parameters to other functions and be called when specific events or operations occur, providing a flexible callback mechanism.

Python entry to proficiency: from zero basics to project development Python entry to proficiency: from zero basics to project development Feb 20, 2024 am 11:42 AM

1. Introduction to Python Python is a general-purpose programming language that is easy to learn and powerful. It was created by Guido van Rossum in 1991. Python's design philosophy emphasizes code readability and provides developers with rich libraries and tools to help them build various applications quickly and efficiently. 2. Python basic syntax The basic syntax of Python is similar to other programming languages, including variables, data types, operators, control flow statements, etc. Variables are used to store data. Data types define the data types that variables can store. Operators are used to perform various operations on data. Control flow statements are used to control the execution flow of the program. 3.Python data types in Python

PHP's object-oriented programming paradigm offers advantages to project management and organizations PHP's object-oriented programming paradigm offers advantages to project management and organizations Sep 08, 2023 am 08:15 AM

PHP's object-oriented programming paradigm provides advantages for project management and organization With the rapid development of the Internet, websites and applications of all sizes have sprung up. In order to meet the growing needs and improve development efficiency and maintainability, the use of object-oriented programming (Object-Oriented Programming, OOP for short) has become the mainstream of modern software development. In dynamic scripting languages ​​like PHP, OOP brings many advantages to project management and organization. This article will introduce

'Introduction to Object-Oriented Programming in PHP: From Concept to Practice' 'Introduction to Object-Oriented Programming in PHP: From Concept to Practice' Feb 25, 2024 pm 09:04 PM

What is object-oriented programming? Object-oriented programming (OOP) is a programming paradigm that abstracts real-world entities into classes and uses objects to represent these entities. Classes define the properties and behavior of objects, and objects instantiate classes. The main advantage of OOP is that it makes code easier to understand, maintain and reuse. Basic Concepts of OOP The main concepts of OOP include classes, objects, properties and methods. A class is the blueprint of an object, which defines its properties and behavior. An object is an instance of a class and has all the properties and behaviors of the class. Properties are characteristics of an object that can store data. Methods are functions of an object that can operate on the object's data. Advantages of OOP The main advantages of OOP include: Reusability: OOP can make the code more

PHP extension development: How to design custom functions to support object-oriented programming? PHP extension development: How to design custom functions to support object-oriented programming? Jun 01, 2024 pm 03:40 PM

PHP extensions can support object-oriented programming by designing custom functions to create objects, access properties, and call methods. First create a custom function to instantiate the object, and then define functions that get properties and call methods. In actual combat, we can customize the function to create a MyClass object, obtain its my_property attribute, and call its my_method method.

The role of golang functions in object-oriented programming The role of golang functions in object-oriented programming Apr 26, 2024 am 09:24 AM

In the Go language, functions play a key role in object-oriented programming: Encapsulation: encapsulating behavior and operating objects. Operations: Perform operations on objects, such as modifying field values ​​or performing tasks.

See all articles