>  기사  >  웹 프론트엔드  >  JavaScript의 범위 안전 생성자 예제 코드에 대한 자세한 설명

JavaScript의 범위 안전 생성자 예제 코드에 대한 자세한 설명

伊谢尔伦
伊谢尔伦원래의
2017-07-20 10:27:551004검색

범위 안전 생성자

생성자는 실제로 new 연산자를 사용하여 호출되는 함수입니다


function Person(name,age,job){
  this.name=name;
  this.age=age;
  this.job=job;
}
var person=new Person('match',28,'Software Engineer');
console.log(person.name);//match

new 연산자를 사용하지 않으면 원래 Person 개체를 대상으로 한 세 가지 속성이 window 개체에 추가됩니다.


function Person(name,age,job){
  this.name=name;
  this.age=age;
  this.job=job;
}     
var person=Person('match',28,'Software Engineer');
console.log(person);//undefined
console.log(window.name);//match

창의 이름 속성은 링크 대상과 프레임을 식별하는 데 사용됩니다. 여기서 이 속성을 실수로 덮어쓰면 페이지에서 다른 오류가 발생할 수 있습니다. 이 문제에 대한 해결책은 범위 안전 생성자를 만드는 것입니다.

function Person(name,age,job){
  if(this instanceof Person){
    this.name=name;
    this.age=age;
    this.job=job;
  }else{
    return new Person(name,age,job);
  }
}
var person=Person('match',28,'Software Engineer');
console.log(window.name); // ""
console.log(person.name); //'match'
var person= new Person('match',28,'Software Engineer');
console.log(window.name); // ""
console.log(person.name); //'match'

그러나 생성자 훔치기 패턴을 상속하면 부작용이 발생합니다. 이는 다음 코드에서 이 객체가 Polygon 객체 인스턴스가 아니기 때문에 생성자 Polygon()이 새 인스턴스를 생성하고 반환하기 때문입니다.


function Polygon(sides){
  if(this instanceof Polygon){
    this.sides=sides;
    this.getArea=function(){
      return 0;
    }
  }else{
    return new Polygon(sides);
  }
}
function Rectangle(wifth,height){
  Polygon.call(this,2);
  this.width=this.width;
  this.height=height;
  this.getArea=function(){
    return this.width * this.height;
  };
}
var rect= new Rectangle(5,10);
console.log(rect.sides); //undefined

범위 안전 생성자 도용 패턴을 사용하려는 경우 , 프로토타입 체인 상속과 결합하여 Rectangle의 프로토타입 속성을 다시 작성하여 인스턴스도 Polygon의 인스턴스가 되도록 해야 합니다

function Polygon(sides){
  if(this instanceof Polygon){
    this.sides=sides;
    this.getArea=function(){
      return 0;
    }
  }else{
    return new Polygon(sides);
  }
}
function Rectangle(wifth,height){
  Polygon.call(this,2);
  this.width=this.width;
  this.height=height;
  this.getArea=function(){
    return this.width * this.height;
  };
}
Rectangle.prototype= new Polygon();
var rect= new Rectangle(5,10);
console.log(rect.sides); //2

위 내용은 JavaScript의 범위 안전 생성자 예제 코드에 대한 자세한 설명의 상세 내용입니다. 자세한 내용은 PHP 중국어 웹사이트의 기타 관련 기사를 참조하세요!

성명:
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.