1. 程式人生 > >JS的prototype、apply、call

JS的prototype、apply、call

prot 為什麽 什麽 name rcc 方法 ole cbo xen

1:原生鏈:prototype

  兒子能夠繼承父親的屬性,也可以覺得遺傳基因不好自己改屬性,(但是不能改變老爸的屬性)。

看例子:

            function farther(){
this.name = "jack",
this.sex = "man",
this.age = 18;
this.cbo = function(){
console.log(this.name);
}
}
// 繼承
farther.prototype = {
son:function(){
this.name = "jack-two";
//  使用自己的name和父類的sex
console.log(this.name +"\t"+ this.sex);
// 更改父類的方法。
this.cbo = function(){
console.log("cbo change.");
};
this.cbo();
}
}
new farther().cbo(); // 輸出 jack
new farther().son(); // 輸出jack 和 jack-two 加 man 加 cbo change.
new farther().cbo(); // 輸出的值依然是 jack;子類不能更改父類屬性

2:call(list) 和 apply(arry) :

  用法1: 對象1.方法.call(對象2),

        對象1的方法使用對象2的屬性,

  用法2: 對象1.call(對象2); 對象2.對象1的方法,

        在對象2中使用對象1的方法。

用法不一樣,效果是一樣的,一個缺少方法,一個缺少屬性。

  為什麽要把 call 和 apply 放一起呢?因為他們除了參數,其效果是一樣的。

            function NameShowing(sex, age) {
this.showName = function() {
console.log(this.name + "\t" + sex + "\t" + age);
}
}
function Person(name) {
this.yourCC = function(){
console.log(name)
}
this.name = name;
};
// 實例化對象
var nameShowing = new NameShowing();
var jeremy = new Person("Jeremy")
//替換this指向 jeremy
NameShowing.apply(jeremy, ["girl",18]);
jeremy.showName();
// 當然可以利用 call(this) 來聯合2個對象
function cExent(name,sex,age) {
NameShowing.call(this,sex,age);
Person.call(this,name);
}
// 這會執行fobj
var c2 = new cExent("jack","man",18);
// 調用NameShowing的myName方法
c2.showName();
c2.yourCC("my name is jack"); // 輸出 jack,因為實例化的時候用的是jack

JS的prototype、apply、call