【发布时间】:2018-11-21 05:59:27
【问题描述】:
我正在做一些测试,但我不知道为什么如果使用 call 我从另一个对象继承,例如 const objC = funcB.call(objA,'Erades') 我得到了一个对象,但是如果我从一个函数继承,我会得到一个具有有线(对我而言)行为的函数。
我不明白为什么要获得方法 B 我必须这样做 funcC.getLastName()
如果有人可以帮助我理解这一点......
TIA
// testing Call to inherit objects / functions
// -------------------------------------------
// we declare our first function
const funcA = function(firstName) {
this.firstName = firstName;
this.getFirstName = function() {
return 'My name is ' + this.firstName;
};
return this;
};
// Create an object out of that function
const objA = new funcA('Rodrigo');
// declare second function
const funcB = function (lastName) {
this.lastName = lastName;
this.getLastName = function() {
return 'My last name is ' + this.lastName;
};
return this;
};
// Create an Object from funcB and ObjectA
const objC = funcB.call(objA,'Erades');
// We get an object
console.log("TYPE OF: ", typeof objC)
console.log('raw:', objC);
console.log('method A: ', objC.getFirstName());
console.log('prop A: ', objC.firstName);
console.log('method B: ', objC.getLastName());
console.log('prop B: ', objC.lastName);
console.log('------------');
// if we don't want to create an object out of a function and an object,
// we could also inherit two functions, but the result really surprise me
const funcC = funcB.call(funcA,'Alonso');
// We get a function !!!!!
console.log("TYPE OF: ", typeof funcC);
console.log('raw:', funcC);
// To get result we need to do this:
console.log('method ==>: ', funcC('Rui'));
console.log('method A: ', funcC('Rui').getFirstName());
console.log('prop A: ', funcC('Maria').firstName);
console.log('method B: ', funcC.getLastName()); // looks like static method ???
console.log('prop B: ', funcC.lastName);
console.log('------------');
【问题讨论】:
标签: javascript inheritance prototype call apply