program tip

프로토 타입을 사용하는 경우 자바 스크립트

radiobox 2020. 9. 7. 07:59
반응형

프로토 타입을 사용하는 경우 자바 스크립트


js에서 프로토 타입 메서드를 사용하는 것이 적절한시기를 이해하고 싶습니다. 항상 사용해야합니까? 아니면 사용이 선호되지 않거나 성능이 저하되는 경우가 있습니까?

이 사이트에서 js의 네임 스페이스를위한 일반적인 방법을 검색 할 때 대부분은 프로토 타입 기반이 아닌 구현을 사용하는 것으로 보입니다. 단순히 개체 또는 함수 개체를 사용하여 네임 스페이스를 캡슐화하는 것입니다.

클래스 기반 언어에서 왔기 때문에 병렬을 시도하고 그리지 않고 프로토 타입이 "클래스"와 같고 내가 언급 한 네임 스페이스 구현이 정적 메서드와 같다고 생각하는 것은 어렵습니다.


프로토 타입은 최적화 입니다.

그것들을 잘 사용하는 좋은 예는 jQuery 라이브러리입니다. 를 사용하여 jQuery 객체를 얻을 때마다 $('.someClass')해당 객체에는 수십 개의 "메서드"가 있습니다. 라이브러리는 객체를 반환하여이를 달성 할 수 있습니다.

return {
   show: function() { ... },
   hide: function() { ... },
   css: function() { ... },
   animate: function() { ... },
   // etc...
};

그러나 이는 메모리의 모든 jQuery 객체가 동일한 메서드를 포함하는 수십 개의 명명 된 슬롯을 계속해서 가질 수 있음을 의미합니다.

대신 이러한 메서드는 프로토 타입에 정의되고 모든 jQuery 객체는 해당 프로토 타입을 "상속"하여 매우 적은 런타임 비용으로 모든 메서드를 얻습니다.

jQuery가 올바르게 작동하는 방법에서 가장 중요한 부분은 이것이 프로그래머에게 숨겨져 있다는 것입니다. 라이브러리를 사용할 때 걱정할 필요가없는 것이 아니라 순전히 최적화로 취급됩니다.

JavaScript의 문제는 네이 키드 생성자 함수가 호출자가 접두사를 기억해야 new한다는 점입니다. 그렇지 않으면 일반적으로 작동하지 않습니다. 이것에 대한 타당한 이유가 없습니다. jQuery는 평범한 함수 뒤에 그 말도 안되는 것을 숨겨서 올바르게 가져 오므로 $객체가 구현되는 방식에 신경 쓸 필요가 없습니다.

지정된 프로토 타입으로 객체를 편리하게 생성 할 수 있도록 ECMAScript 5에는 표준 기능이 포함되어 있습니다 Object.create. 크게 단순화 된 버전은 다음과 같습니다.

Object.create = function(prototype) {
    var Type = function () {};
    Type.prototype = prototype;
    return new Type();
};

생성자 함수를 작성한 다음 new.

언제 프로토 타입을 피하겠습니까?

유용한 비교는 Java 및 C #과 같은 인기있는 OO 언어와의 비교입니다. 이들은 두 가지 상속 유형을 지원합니다.

  • 인터페이스 당신 상속, 같은 클래스가 인터페이스의 모든 구성원에 대한 고유의 구현을 제공.implementinterface
  • 일부 메서드의 기본 구현을 제공 extend하는 구현 상속 class.

JavaScript에서 프로토 타입 상속은 구현 상속 의 일종입니다 . 따라서 (C # 또는 Java에서) 기본 동작을 얻기 위해 기본 클래스에서 파생 된 경우 재정의를 통해 약간 수정 한 다음 JavaScript에서 프로토 타입 상속이 의미가 있습니다.

However, if you're in a situation where you would have used interfaces in C# or Java, then you don't need any particular language feature in JavaScript. There is no need to explicitly declare something that represents the interface, and no need to mark objects as "implementing" that interface:

var duck = {
    quack: function() { ... }
};

duck.quack(); // we're satisfied it's a duck!

In other words, if each "type" of object has its own definitions of the "methods", then there is no value in inheriting from a prototype. After that, it depends on how many instances you allocate of each type. But in many modular designs, there is only one instance of a given type.

And in fact, it has been suggested by many people that implementation inheritance is evil. That is, if there are some common operations for a type, then maybe it's clearer if they are not put into a base/super class, but are instead just exposed as ordinary functions in some module, to which you pass the object(s) you want them to operate on.


You should use prototypes if you wish to declare a "non-static" method of the object.

var myObject = function () {

};

myObject.prototype.getA = function (){
  alert("A");
};

myObject.getB = function (){
  alert("B");
};

myObject.getB();  // This works fine

myObject.getA();  // Error!

var myPrototypeCopy = new myObject();
myPrototypeCopy.getA();  // This works, too.

One reason to use the built-in prototype object is if you'll be duplicating an object multiple times that will share common functionality. By attaching methods to the prototype, you can save on duplicating methods being created per each new instance. But when you attach a method to the prototype, all instances will have access to those methods.

Say you have a base Car() class/object.

function Car() {
    // do some car stuff
}

then you create multiple Car() instances.

var volvo = new Car(),
    saab = new Car();

Now, you know each car will need to drive, turn on, etc. Instead of attaching a method directly to the Car() class (which takes up memory per each instance created), you can attach the methods to the prototype instead (creating the methods only once), therefore giving access to those methods to both the new volvo and saab.

// just mapping for less typing
Car.fn = Car.prototype;

Car.fn.drive = function () {
    console.log("they see me rollin'");
};
Car.fn.honk = function () {
    console.log("HONK!!!");
}

volvo.honk();
// => HONK!!!
saab.drive();
// => they see me rollin'

Put functions on a prototype object when you're going to create lots of copies of a particular kind of object and they all need to share common behaviors. By doing so, you'll save some memory by having just one copy of each function, but that's only the simplest benefit.

Changing methods on prototype objects, or adding methods, instantly changes the nature of all the instances of the corresponding type(s).

Now exactly why you'd do all these things is mostly a function of your own application design, and the kinds of things you need to do in client-side code. (A whole different story would be code inside a server; much easier to imagine doing more large-scale "OO" code there.)


If i explain in class based term then Person is class, walk() is Prototype method. So walk() will have its existence only after you instantiate new object with this.

So if you want to create the copies of object like Person u can create many users Prototype is good solution as it saves memory by sharing/inheriting same copy of function for each of the object in memory.

Whereas static is not that great help in such scenario.

function Person(){
this.name = "anonymous";
}

// its instance method and can access objects data data 
Person.prototype.walk = function(){
alert("person has started walking.");
}
// its like static method
Person.ProcessPerson = function(Person p){
alert("Persons name is = " + p.name);
}

var userOne = new Person();
var userTwo = new Person();

//Call instance methods
userOne.walk();

//Call static methods
Person.ProcessPerson(userTwo);

So with this its more like instance method. The object's approach is like Static methods.

https://developer.mozilla.org/en/Introduction_to_Object-Oriented_JavaScript

참고URL : https://stackoverflow.com/questions/4736910/javascript-when-to-use-prototypes

반응형