本文主要跟大家分享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.函數宣告與函數表達式的區別
函數宣告會提升,在前後都能調用,而函數表達式只能在函數表達式後面調用
1.建構函數中的this指向調用的物件
2.普通函數中的this指向window,嚴格模式下指向undefined;
3.定時器中的this指向window
4.物件方法呼叫this指向呼叫方法的物件
以上是js高階知識講解的詳細內容。更多資訊請關注PHP中文網其他相關文章!