首頁  >  文章  >  web前端  >  js高階知識講解

js高階知識講解

小云云
小云云原創
2018-03-29 17:10:462372瀏覽

本文主要跟大家分享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