欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  web前端

javascript之面向对象编程之属性继承

程序员文章站 2022-04-13 14:52:47
...
在JavaScript中,没有继承关键字: extends。那么,它是通过哪些方法,在用构造函数生成对象时,把对象基于另外一个构造函数,进行属性的生成(继承/拷贝)的呢? 即:对一个函数使用 new 关键字生成对象时,其对象的属性,可以来自于其它函数。

本文提供两种写法:

第一种(非正式):
但需要理解这种用法。

Javascript代码

function Animal (name, age){

this.name = name;

this.age = age;

}

function Dog (name, age){

this.i = Animal;

this.i(name, age);

}

d = new Dog('hello',20);

console.log(d);

/*

Dog {name: "hello", age: 20}

age: 20

i: function Animal(name, age)

name: "hello"

__proto__:

constructor: function Dog(name, age)

*/


上面一种写法是引用外部函数 Animal 作为自己的一个内部成员函数。
这是一种匿名函数的写法。

相当于:

Javascript代码

function Dog (name, age){

this.i = function Animal (name, age){

this.name = name;

this.age = age;

}

this.i(name, age);

}



相当于:

Javascript代码

function Dog (name, age){

/*

When calling a function, instead of using the 'new' keyword to create

object,

// Calling a function

Animal();

//Using the 'new' keyword to create object.

new Animal();

The inner 'this' is the same one of the outer 'this'. Because

there is no 'this' object created inside of the function, so it has to

refer to the outer one.

*/

this.i = function (name, age){

this.name = name; // 2. so the inner "this" is the same

this.age = age; // one of the outer "this".

}

this.i(name, age); // 1. function call, no 'this' created.

}



思考:调用函数时,"this"是谁??
既然,函数调用不生成 "this" 对象。
那么直接在 Dog 内调用 Animal 不可以吗?
答案:否

Java代码

/*

Which 'this' the called function belongs to, the inner 'this' inside of

the called function refers to that 'this' object.

*/

function Dog (name, age){ // if call Animal directly,

Animal(name,age); // the Animal function here belongs to 'window',

} // so 'this' inside of Animal refers to 'window'





第二种(正式):
使用 apply() 函数 或 call() 函数

apply() : apply "this" object to the(that) function, then call it.

Javascript代码

function Animal (name, age){

this.name = name;

this.age = age;

}

function Dog (name, age){

Animal.apply(this, arguments); // apply "this" object to Animal function.

// or

// call Animal function with a given 'this'

// object, instead of referring to other 'this'.

}

d = new Dog('hello',20);

console.log(d);

/*

Dog {name: "hello", age: 20}

age: 20

name: "hello"

__proto__:

constructor: function Dog(name, age)

*/