javascript - Novice, let me ask a basic question about prototype expansion. Can you please give me some guidance?
黄舟
黄舟 2017-05-18 10:58:53
0
3
533

1. The third line of code is not understood.
The third line should be implemented. Add data as the prototype object to super_robot.
Why not SuperRobot.__proto__=data;
but say.__proto__=data; ??
2.

function SuperRobot(data) {
    var say = function() { return "Hello World!"; };
    say.__proto__=data;
    return say;
}

var data = { name:"atom", age: 5};
var super_robot = SuperRobot(data);

console.log(super_robot());            //Hello World!
console.log(super_robot.age);        //5
console.log(typeof super_robot);     //function
黄舟
黄舟

人生最曼妙的风景,竟是内心的淡定与从容!

reply all(3)
曾经蜡笔没有小新
function Fun(){
    var a = {};
    return a;
}
var super = Fun();

Who should be added to at this timesuper等于什么?
是不是等于Fun内声明的a?
所以__proto_.

我想大声告诉你

Writing like this is equivalent to rewriting the prototype chain of super_robot, which cannot be regarded as an extension. Originally, super_robot.__proto__ pointed to Function.prototype. After rewriting, super_robot.__proto__ pointed to the incoming data object. It can be said that after rewriting, super_robot can no longer be regarded as a It is a real function. Now it cannot use the methods on the Function prototype, such as call, apply, bind, etc.

console.log( super_robot instanceof Function ); // false
console.log( super_robot.call ); // undefined

If you extend it, you should write say.__proto__.name = name, say.__proto__.age = age, which is equivalent to Function.prototype.name = name, Function.prototype.age = age, but this will make all function instances accessible. Two attributes, so it is generally not recommended to expand like this

我想大声告诉你

SuperRobot is just a factory function, what it returns is the core

Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template