js高级知识讲解

小云云
小云云原创
2018-03-29 17:10:461911浏览

本文主要和大家分享js高级知识讲解

继承

继承是类型与类型之间的关系;

对象的‘继承’:

实际上是对对象的拷贝

function extend (parent, child) 
{  for (var key in parent) 
{    if (! child[key] )
{      child[key] = parent[key]    
}  
}}

原型继承

只能继承父元素中的方法,属性继承没有意义

//父级元素function Person (name, age, sex)
{  this.name = name;  this.age = age;  
this.sex = sex}Person.prototype.sayHi = function ()
{  console.log('hello' + this.name);}
//子级元素function Student (score) 
{  this.score = score;}
//只能继承方法Student.prototype = new Person;Student.prototype.constructor = Student;var s1 = new Student(100);console.log(s1);

注意:

问题:无法给构造函数设置参数 Student.prototype = new Person ,且只能执行一次,无法给属性传值;

借用构造函数

利用call能改变this的属性,并且可以借用构造函数,但是不能继承构造函数的方法;

//父级元素function Person (name, age, sex)
{  this.name = name;  this.age = age;  this.sex = sex}Person.prototype.sayHi = function ()
{  console.log('hello' + this.name);}
//子级元素function Student (name,age, sex, score) {Person.call(this, name, age, sex);  
this.score = score;}
//只能继承属性var s1 = new Student('na', 20, 'nv' , 100);console.log(s1);

原型+ 构造函数

把原型和构造函数两种情况结合:但会出现一个问题,一个子级元素的方法会被多个子级元素访问;

如何解决这个问题,则用到了对象的继承即拷贝;

function extend (parent, child) 
{  for (var key in parent) 
{    if (! child[key] )
{      child[key] = parent[key]   
 }  }}function Person (name, age, sex)
 {  this.name = name;  this.age = age; 
  this.sex = sex}Person.prototype.sayHi = function ()
  {  console.log('hello' + this.name); }
  //子级元素function Student (name,age, sex, score) 
  {Person.call(this, name, age, sex);  
  this.score = score;}Student.prototype.say = function ()
  {  console.log('hi'); }
  //只能继承属性extend(Person.prototype, Student.prototype);var s1 = new Student('na', 20, 'nv' , 100);console.log(s1);
  //子级元素function Teacher (name,age, sex,salary) {Person.call(this, name, age, sex);  this.salary = salary}extend(Person.prototype, 
  Teacher.prototype);var t = new Teacher('na', 10,'nv', 1000);console.log(t);

函数进阶

函数的定义方式

1.函数声明

function fn() {

}

2.函数表达式

var fn = function (){

}

3.var fn = new Function('参数是字符串');

这里的fn即使对象又是函数

4.函数声明与函数表达式的区别

函数声明会提升,在前后都能调用,而函数表达式只能在函数表达式后面调用

应用到this的场景

1.构造函数中的this指向调用的对象

2.普通函数中的this指向window,严格模式下指向undefined;

3.定时器中的this指向window

4.对象方法调用this指向调用方法的对象

改变this的指向

1.bind:

第一个参数指向this要指向的元素;

返回一个新的函数;

2.call

会调用函数,改变this的指向

借用构造函数

借用其他对象的方法

3.apply

第一个参数是改变的this的指向,第二个参数是一个数组;

相关推荐:

JS高级相关知识

以上就是js高级知识讲解的详细内容,更多请关注php中文网其它相关文章!

声明:本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn核实处理。