Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

JavaScript 函数继承的几种方法 #96

Open
kvkens opened this issue Aug 5, 2016 · 0 comments
Open

JavaScript 函数继承的几种方法 #96

kvkens opened this issue Aug 5, 2016 · 0 comments

Comments

@kvkens
Copy link
Member

kvkens commented Aug 5, 2016

主要记录一些工作中常见用到的代码,比较基础高手莫笑~

1、 原型继承方式

function Person(name,age){
    this.name = name;
    this.age = age;
}

Person.prototype.sayHello = function(){
    console.log("使用原型得到名字:%s,年龄:%d",this.name,this.age);
}

function Student(){

}
Student.prototype = new Person("Jay",37);
Student.prototype.grade=5;
Student.prototype.tips=function(){
    console.log("我是从Student来的,年级是%d,继承来的%s",this.grade,this.name);
}

var stu = new Student();
stu.tips();

  • 首先我们创建一个方法作为父类Person,再创建一个方法作为子类Student,子类用原型去接收父类构造函数,这样做一个指向关系从而达到子类继承父类方法。子类也可以添加自己的方法,这样最后在实例化子类Student的时候,可以从原型上拿到父类指向的函数。利用了原型链的特性每一级别的查找。

2、 构造函数方式

//父类函数
function Parent(name){
    this.name = name;
    this.sayHello = function(){
        console.log("Parent Name : %s",this.name);
    }
}

//子类函数
function Child(name,age){
    this.tempMethod = Parent;
    this.tempMethod(name);
    this.age = age;
    this.sayChild = function(){
        console.log("Child Name:%s,Age:%d",this.name,this.age);
    }
}
//测试继承
var p = new Parent("Kvkens");
p.sayHello();

var c = new Child("Kvkens",29);
c.sayChild();
  • 构造函数是用到了一个中间函数作为中间人,接收Parent函数,并且调用中间函数传入相应构造参数,这里能够直接调用Parent是因为当然环境是实例化,都是在new的时候发生的,并不是静态的函数。

3、 call、apply 方式

function Animal(name,age,love){
    this.name = name;
    this.age = age;
    this.love = love;
    this.sayHi = function(){
        console.log("Animal name:%s,age:%d,love:%s",this.name,this.age,this.love);
    }
}

function Dog(name,age,love){
    Animal.call(this,name,age,true);
}
var dog = new Dog("xiaobai",5,true);
dog.sayHi();

  • 非常简单的继承实现,采用侵入式作用域劫持方式,我说的和别人解释的不一样,只是我自己的理解,如说的不对请指出,代码会写,有的时候却不能说出为什么是这样,都是自己的理解,见谅!

(完)

@kvkens kvkens added js and removed js labels Aug 5, 2016
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant