>  기사  >  웹 프론트엔드  >  JavaScript 객체지향 본질 (2)

JavaScript 객체지향 본질 (2)

黄舟
黄舟원래의
2017-03-06 14:29:201123검색

JavaScript 객체지향 필수 (1)

생성자와 프로토타입 객체

생성자도 함수인데, new로 객체를 생성할 때 호출되는 함수이고, 일반 함수와의 한 가지 차이점은 첫 글자를 대문자로 써야 한다는 것입니다. 하지만 생성자를 일반 함수로 호출하는 경우(new 키워드가 누락됨) 이것이 가리키는 문제에 주의해야 합니다.

var name = "Pomy";
function Per(){
    console.log("Hello "+this.name);
}
var per1 = new Per();  //"Hello undefined"
var per2 = Per();   //"Hello Pomy"

new를 사용하면 이 객체가 자동으로 생성됩니다. 해당 유형은 생성자 유형이며 new 키워드 없이 객체 인스턴스를 가리키며, 이는 전역 객체를 가리킵니다.

instanceof를 사용하여 객체 유형을 감지할 수 있습니다. 동시에 각 객체는 생성될 때 해당 생성자를 가리키는 생성자 속성(리터럴 형식으로 생성된 객체 또는 Object를 가리키는 객체 생성자)을 갖습니다. , 사용자 정의 생성자 함수에 의해 생성된 객체는 해당 생성자를 가리킵니다.

console.log(per1 instanceof Per);  //true
console.log(per1.constructor === Per); //true

각 객체 인스턴스에는 객체의 프로토타입 객체를 가리키는 내부 속성인 [[Prototype]]이 있습니다. 생성자 자체에도 프로토타입 객체를 가리키는 프로토타입 속성이 있습니다. 생성된 모든 객체는 이 프로토타입 객체의 속성과 메서드를 공유합니다.

function Person(){}
Person.prototype.name="dwqs";
Person.prototype.age=20;
Person.prototype.sayName=function()
{
    alert(this.name);
};
var per1 = new Person();
per1.sayName();  //dwqs
var per2 = new Person();
per2.sayName();  //dwqs
alert(per1.sayName == per2.sayName);  //true

따라서 인스턴스의 포인터는 생성자가 아닌 프로토타입만 가리킵니다. ES5는 프로토타입 객체와 인스턴스 사이의 관계를 반영하기 위해 hasOwnProperty() 및 isPropertyOf() 메소드를 제공합니다

alert(Person.prototype.isPrototypeOf(per2));  //true
per1.blog = "www.ido321.com";
alert(per1.hasOwnProperty("blog"));  //true
alert(Person.prototype.hasOwnProperty("blog"));  //false
alert(per1.hasOwnProperty("name"));  //false
alert(Person.prototype.hasOwnProperty("name"));  //true

프로토타입 객체의 constructor 속성은 생성자 자체를 가리키므로 다시 작성할 때 생성자에 주의해야 합니다. 프로토타입 속성 포인팅 문제.

function Hello(name){
    this.name = name;
}
//重写原型
Hello.prototype = {
    sayHi:function(){
        console.log(this.name);
    }
};
var hi = new Hello("Pomy");
console.log(hi instanceof Hello);  //true
console.log(hi.constructor === Hello); //false
console.log(hi.constructor === Object); //true

객체 리터럴 형식을 사용하여 프로토타입 객체를 다시 작성하면 생성자의 속성이 변경되므로 생성자는 Hello 대신 Object를 가리킵니다. 생성자 포인터가 중요한 경우 프로토타입 객체를 다시 작성할 때 생성자 속성을 수동으로 재설정해야 합니다

Hello.prototype = {
    constructor:Hello,
    sayHi:function(){
        console.log(this.name);
    }
};
console.log(hi.constructor === Hello); //true
console.log(hi.constructor === Object); //false

프로토타입 객체의 특성을 사용하여 JavaScript의 내장 프로토타입 객체에 사용자 정의 메서드를 쉽게 추가할 수 있습니다. :

Array.prototype.sum=function(){
    return this.reduce(function(prev,cur){
        return prev+cur;
    });
};
var num = [1,2,3,4,5,6];
var res = num.sum();
console.log(res);  //21
String.prototype.capit = function(){
    return this.charAt(0).toUpperCase()+this.substring(1);
};
var msg = "hello world";
console.log(msg.capit()); //"Hello World"

상속

[[Prototype]] 기능을 사용하면 리터럴 형식의 객체에 대한 프로토타입 상속을 구현할 수 있습니다. Object.prototype은 암시적으로 [[Prototype]으로 지정됩니다. ], 또한 두 개의 매개변수를 허용하는 Object.create()를 통해 명시적으로 지정할 수 있습니다. 첫 번째는 [[Prototype]](프로토타입 객체)이 가리키는 객체이고 두 번째는 선택적 속성 설명자 객체입니다.

var book = {
    title:"这是书名";
};
//和下面的方式一样
var book = Object.create(Object.prototype,{
    title:{
        configurable:true,
        enumerable:true,
        value:"这是书名",
        wratable:true
    }
});

리터럴 객체는 기본적으로 Object에서 상속됩니다. 더 흥미로운 사용법은 사용자 정의 객체 간의 상속을 구현하는 것입니다.

var book1 = {
    title:"JS高级程序设计",
    getTitle:function(){
        console.log(this.title);
    }
};
var book2 = Object.create(book1,{
    title:{
        configurable:true,
        enumerable:true,
        value:"JS权威指南",
        wratable:true
    }
});
book1.getTitle();  //"JS高级程序设计"
book2.getTitle();  //"JS权威指南"
console.log(book1.hasOwnProperty("getTitle"));  //true
console.log(book1.isPrototypeOf("book2"));  //false
console.log(book2.hasOwnProperty("getTitle"));  //false

book2의 getTitle 속성에 액세스하면 JavaScript 엔진이 검색 프로세스를 수행합니다. 이제 book2의 자체 속성을 검색하고, 발견되지 않으면 [[Prototype]]을 검색합니다. , 없으면 상속 체인이 끝날 때까지 프로토타입 객체의 [[Prototype]]을 계속 검색합니다. 끝은 일반적으로 [[Prototype]]이 null로 설정된 Object.prototype입니다.

상속을 구현하는 또 다른 방법은 생성자를 사용하는 것입니다. 각 함수에는 기본적으로 Object.prototype에서 상속되도록 자동으로 설정되는 쓰기 가능한 프로토타입 속성이 있습니다. 프로토타입 체인을 덮어써서 변경할 수 있습니다.

function Rect(length,width){
    this.length = length;
    this.width = width;
}
Rect.prototype.getArea = function(){
    return this.width * this.length;
};
Rect.prototype.toString = function(){
    return "[Rect"+this.length+"*"+this.width+"]";
};
function Square(size){
    this.length = size;
    this.width = size;
}
//修改prototype属性
Square.prototype = new Rect();
Square.prototype.constructor = Square;
Square.prototype.toString = function(){
    return "[Square"+this.length+"*"+this.width+"]";
};
var rect = new Rect(5,10);
var square = new Square(6);
console.log(rect.getArea());  //50
console.log(square.getArea());  //36

상위 클래스의 toString()에 액세스하려면 다음과 같이 하면 됩니다.

Square.prototype.toString = function(){
    var text = Rect.prototype.toString.call(this);
    return text.replace("Rect","Square");
}

위는 JavaScript 객체지향 본질(2)의 내용입니다. 관련 내용은 PHP 중국어 홈페이지(www.php.cn)를 주목해주세요!

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