标签:on() class ... 注意 查询 tuple 成员 资料 create
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
/** * 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 test var 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 test var p_man = new Man(); p_man.f_say("hello"); // Man继承了Person中的f_say成员方法
// apply function 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
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
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,构造函数
标签:on() class ... 注意 查询 tuple 成员 资料 create
原文地址:http://www.cnblogs.com/suyuan1573/p/6130636.html