Home > Web Front-end > JS Tutorial > body text

Example parsing js prototype and call()

小云云
Release: 2018-02-24 14:21:12
Original
1385 people have browsed it

This article mainly shares with you js prototype and call(). We have made a small summary of js prototype and call(), hoping to help everyone.

/*
原型也是一个对象
把共有的属性或者方法放在原型中
*/

//Person.prototype 原型
/*Person.prototype = { } 祖先*/
Person.prototype.name = "这是祖先的名称 ";
/*多个属性可以这样定义*/
Person.prototype = {
    age : 20,
    sex :"女",
    constructor : Car
}
/*构造函数*/
function Person(sex){
    this.sex =sex;
}

function Car() {
}

/*子孙类可以继承父类的属性和方法,但是子类对象不能修改父类的对象的属性,只能自己进行操作才可以实现
也就是说person.name= "这是祖先的名称 "
*/
 var person = new Person();
/*constructor是对象的构造函数*/
console.log(person.constructor)


Animal.prototype.name = "这是个动物的类";
function Animal() {

    /*这里可以理解为放对象没有这个属性的时候才会去原型中查找,其中也可以改变原型的指向*/
//    var this ={
//     _proto_ : Animal.prototype
// }
}

var animal = new Animal();

//其中注意一下两种写法
Animal.prototype.name = " 这是另外一个动物的类";   //打印Animal.prototype.name = " 这是另外一个动物的类";这个可以这样理解修改的是属性

Animal.prototype = {
    name : " 这是另外一个动物"
}
// Animal.prototype.name = " 这是个动物的类";

/*创建对象*/
var obj = Object.create(原型);


/*call 和apply的作用*/
function Person1(name, age) {
    /*其中这里的this == object*/
    this.name = name;
    this.age = age;
}

/*这里的Student调用Person1的函数*/
function Student (name, age ,grade) {
    /*Person1.apply(this , [name, age]);*/
    Person1.call(this ,name,age);
    this.grade =grade;
}

var student = new Student('JJJJJ',20,1);


var person1 = new Person1('ZK',100);
var object = {

}
/*call的作用是:改变this的指向*/
Person1.call(object ,'zhe',52);
Copy after login

Related recommendations:

Four Steps of JS Prototype Inheritance

Recommended 7 articles about js prototype chain

Several details of js prototype chain inheritance Blog classification: JavaScript

The above is the detailed content of Example parsing js prototype and call(). For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template