search
HomeWeb Front-endJS TutorialJavaScript does not use prototype and new to implement inheritance mechanism_javascript tips

This method is not the author’s original creation. I just summarized it on the basis of my predecessors and came up with a simple and practical JavaScript inheritance method.

Traditional JavaScript inheritance is based on the prototype prototype chain, and requires the use of a large number of new operations. The code is not concise enough, the readability is not very strong, and it seems to be susceptible to prototype chain pollution.

The inheritance method summarized by the author is concise and clear. Although it is not the best method, I hope it can inspire readers.

Okay, no more nonsense, just look at the code, the comments are detailed, you can understand it at a glance~~~

Copy code The code is as follows:

 /**
* 14-11-11에 Yang Yuan이 작성했습니다.
* 프로토타입을 사용하지 않고 상속 구현
*
​*/
 /**
* 자바스크립트 객체 복사, 하나의 레이어만 복사되고 함수 속성만 복사되는데 이는 보편적이지 않습니다!
* @param obj 복사할 객체
* @returns 객체
​*/
 Object.prototype.clone = 함수(){
     var _s = 이것,
         newObj = {};
     _s.each(함수(키, 값){
         if(Object.prototype.toString.call(value) === "[객체 함수]"){
             newObj[키] = 값;
         }
     });
     newObj 반환;
 };
 /**
* obj의 모든 속성을 탐색하세요
*
* @param 콜백 콜백 함수. 콜백에는 키 속성 이름, 값 속성 값
이라는 두 가지 매개변수가 포함됩니다. ​*/
 Object.prototype.each = 함수(콜백){
     var 키 = "",
         _이것=이것;
     for (_this를 입력하세요){
         if(Object.prototype.hasOwnProperty.call(_this, key)){
             콜백(키, _this[키]);
         }
     }
 };
 /**
* 하위 클래스 생성
* @param ext obj에는 다시 작성하거나 확장해야 하는 메서드가 포함되어 있습니다.
* @returns 객체
​*/
 Object.prototype.extend = 함수(ext){
     var child = this.clone();
     ext.each(함수(키, 값){
         자식[키] = 값;
     });
     아이를 돌려보내세요;
 };
 /**
* 객체(인스턴스) 생성
* @param 인수는 생성자 매개변수 목록으로 임의 개수의 매개변수를 허용합니다
* @returns 객체
​*/
 Object.prototype.create = function(){
     var obj = this.clone();
     if(obj.construct){
         obj.construct.apply(obj, 인수);
     }
     obj 반환;
 };
 /**
* 사용예
* 번거로운 프로토타입과 새로운 것을 피하기 위해 이 상속 방법을 사용하십시오.
* 하지만 저자가 작성한 현재 예제에서는 부모 클래스의 기능(멤버 메서드로 이해 가능)만 상속할 수 있습니다.
* 더욱 풍부한 콘텐츠를 상속받고 싶다면 복제 방식을 개선해 주세요.
*
*
​*/
 /**
* 동물(부모클래스)
* @type {{construct: 구성하다, 먹다: 먹다}}
​*/
 var 동물 = {
     구성: 함수(이름){
         this.name = 이름;
     },
     먹다: function(){
         console.log("내 이름은 "this.name"입니다. 먹을 수 있어요!");
     }
 };
 /**
* 새(하위 카테고리)
* Birds는 상위 클래스의 eat 메소드를 재정의하고 fly 메소드를 확장합니다
* @type {하위 클래스|void}
​*/
 var Bird = Animal.extend({
     먹다: 기능(음식){
         console.log("내 이름은 " this.name "입니다. " 음식 "을 먹을 수 있어요!");
     },
     파리: 함수(){
         console.log("나는 날 수 있어요!");
     }
 });
 /**
* 새 인스턴스 생성
* @type {짐}
​*/
 var BirdJim = Bird.create("짐"),
     BirdTom = Bird.create("톰");
 BirdJim.eat("벌레");  //제 이름은 짐이에요. 벌레도 먹을 수 있어요!
 BirdJim.fly();  //날 수 있어요!
 BirdTom.eat("쌀");  //제 이름은 톰입니다. 밥 먹을 수 있어요!
 새Tom.fly();  //날 수 있어요!
Statement
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
Python vs. JavaScript: A Comparative Analysis for DevelopersPython vs. JavaScript: A Comparative Analysis for DevelopersMay 09, 2025 am 12:22 AM

The main difference between Python and JavaScript is the type system and application scenarios. 1. Python uses dynamic types, suitable for scientific computing and data analysis. 2. JavaScript adopts weak types and is widely used in front-end and full-stack development. The two have their own advantages in asynchronous programming and performance optimization, and should be decided according to project requirements when choosing.

Python vs. JavaScript: Choosing the Right Tool for the JobPython vs. JavaScript: Choosing the Right Tool for the JobMay 08, 2025 am 12:10 AM

Whether to choose Python or JavaScript depends on the project type: 1) Choose Python for data science and automation tasks; 2) Choose JavaScript for front-end and full-stack development. Python is favored for its powerful library in data processing and automation, while JavaScript is indispensable for its advantages in web interaction and full-stack development.

Python and JavaScript: Understanding the Strengths of EachPython and JavaScript: Understanding the Strengths of EachMay 06, 2025 am 12:15 AM

Python and JavaScript each have their own advantages, and the choice depends on project needs and personal preferences. 1. Python is easy to learn, with concise syntax, suitable for data science and back-end development, but has a slow execution speed. 2. JavaScript is everywhere in front-end development and has strong asynchronous programming capabilities. Node.js makes it suitable for full-stack development, but the syntax may be complex and error-prone.

JavaScript's Core: Is It Built on C or C  ?JavaScript's Core: Is It Built on C or C ?May 05, 2025 am 12:07 AM

JavaScriptisnotbuiltonCorC ;it'saninterpretedlanguagethatrunsonenginesoftenwritteninC .1)JavaScriptwasdesignedasalightweight,interpretedlanguageforwebbrowsers.2)EnginesevolvedfromsimpleinterpreterstoJITcompilers,typicallyinC ,improvingperformance.

JavaScript Applications: From Front-End to Back-EndJavaScript Applications: From Front-End to Back-EndMay 04, 2025 am 12:12 AM

JavaScript can be used for front-end and back-end development. The front-end enhances the user experience through DOM operations, and the back-end handles server tasks through Node.js. 1. Front-end example: Change the content of the web page text. 2. Backend example: Create a Node.js server.

Python vs. JavaScript: Which Language Should You Learn?Python vs. JavaScript: Which Language Should You Learn?May 03, 2025 am 12:10 AM

Choosing Python or JavaScript should be based on career development, learning curve and ecosystem: 1) Career development: Python is suitable for data science and back-end development, while JavaScript is suitable for front-end and full-stack development. 2) Learning curve: Python syntax is concise and suitable for beginners; JavaScript syntax is flexible. 3) Ecosystem: Python has rich scientific computing libraries, and JavaScript has a powerful front-end framework.

JavaScript Frameworks: Powering Modern Web DevelopmentJavaScript Frameworks: Powering Modern Web DevelopmentMay 02, 2025 am 12:04 AM

The power of the JavaScript framework lies in simplifying development, improving user experience and application performance. When choosing a framework, consider: 1. Project size and complexity, 2. Team experience, 3. Ecosystem and community support.

The Relationship Between JavaScript, C  , and BrowsersThe Relationship Between JavaScript, C , and BrowsersMay 01, 2025 am 12:06 AM

Introduction I know you may find it strange, what exactly does JavaScript, C and browser have to do? They seem to be unrelated, but in fact, they play a very important role in modern web development. Today we will discuss the close connection between these three. Through this article, you will learn how JavaScript runs in the browser, the role of C in the browser engine, and how they work together to drive rendering and interaction of web pages. We all know the relationship between JavaScript and browser. JavaScript is the core language of front-end development. It runs directly in the browser, making web pages vivid and interesting. Have you ever wondered why JavaScr

See all articles

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

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

DVWA

DVWA

Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software

Atom editor mac version download

Atom editor mac version download

The most popular open source editor

VSCode Windows 64-bit Download

VSCode Windows 64-bit Download

A free and powerful IDE editor launched by Microsoft

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

Powerful PHP integrated development environment