標籤:on() class ... 注意 查詢 tuple 成員 資料 create
javascript中繼承可以通過call、apply、protoperty實現1.callcall的含義:foo.call(thisObject, args...)表示函數foo調用的時候,環境切換為thisObject,意思是用thisObject來調用foo方法,如果沒有指定thisObject,則外部的Global對象被用作預設的thisObject
function foo() { if (!this.s_name) { // 避免被this的屬性重新賦值 this.s_name = "inside foo"; } console.info(this.s_name);}function bar() { if (!this.s_name) { this.s_name = "inside bar"; }}var p = new bar();foo.call(p);// foo函數調用,由於使用了call,其環境切換成p,foo函數中的this指向p output:inside foo 用call來實現繼承:
/** * Created by Administrator on 2016/12/4 0004. */function Person() { this.s_name = "Person" this.s_age = undefined; this.s_gender = undefined; this.f_say = function (txt) { console.info("%s say:%s", this.s_name, txt) }}// Person testvar p = new Person();p.f_say(‘hello‘); // Person對象的正常調用// Man 繼承了Person中所有的屬性和方法function Man() { Person.call(this, this.arguments);// 這裡理解下,Person()函數調用過程中,this執行Man,this.f_say=function(){}其實就是給Man執行的,可以認為給Man添加了幾個屬性和方法 this.s_name = "Man"; // 注意,如果這句話放在第一行,將被Person的建構函式中的this.s_name = "Person"重新賦值 this.f_playGame = function () { console.info("Man like play game"); }}// Man testvar p_man = new Man();p_man.f_say("hello"); // Man繼承了Person中的f_say成員方法
2.apply,除了參數不同,和call完全一樣,這裡還是介紹下apply的含義:foo.apply(bar, tuple_arg)表示調用foo函數的時候,內部涉及到this的都指向bar,這個例子要比前面的call的例子好;
// applyfunction foo(arg1, arg2) { this.s_name = "foo"; this.f_func = function (arg1, arg2) { console.info(this.s_name + " " + arg1 + " " + arg2);// 這裡的arg會按照範圍鏈和原型鏈綜合尋找 }}function bar() { this.s_name = "bar";}var f = new foo("foo_arg1", "foo_arg2");var b = new bar();f.f_func.apply(b, ["apply_arg1", "apply_arg2"]); //調用foo類型的對象f中的f_func 方法,但是裡面的this.s_name 其實是bar類型的對象b的output:bar apply_arg1 apply_arg2繼承的例子就不寫, 和call一樣,在Man()方法中調用Person.apply(this, []), 從而將Person() 中的this.* = * 執行了一遍,this其實是Man() 3. js原型(prototype)實現繼承,具體的原理稍微有點複雜,可以查詢其他資料
function Person() { this.s_name = "Person"; this.f_say = function () { console.info(this.s_name) }}function Man() { this.s_name = "Man";}Man.prototype = new Person()var p = new Man();p.f_say(); output:Man
4.建構函式該方法和call 以及apply其實一個意思,只不過通過不同的途徑來保證父函數執行時,裡面的this是自己
function Person() { this.s_name = "Person"; this.f_say = function () { console.info(this.s_name); }}function Man() { this.parent_method = Person; this.parent_method(this.arguments); // 執行時Person函數,裡面的this其實是Man this.s_name = "Man"; // 如果放在第一行,會被Person() 的執行覆蓋}var p = new Man(); p.f_say(); output:Man
javascript 中的繼承實現, call,apply,prototype,建構函式