Javascript 为什么这个方法没有方法打印
我相信这是非常非常简单的,但是为什么下面的方法不起作用呢Javascript 为什么这个方法没有方法打印,javascript,Javascript,我相信这是非常非常简单的,但是为什么下面的方法不起作用呢 var o = function() { }; o.prototype.print = function( ) { console.log("hi") }; o.print(); // console message: Object function o() { } has no method 'print' 拨弄 更新 为什么这也不起作用 var o = function() { }; o.prototype.print = func
var o = function() { };
o.prototype.print = function( ) { console.log("hi") };
o.print(); // console message: Object function o() { } has no method 'print'
拨弄
更新
为什么这也不起作用
var o = function() { };
o.prototype.print = function( ) { console.log("hi") };
var c = Object.create( o );
c.print();
如果需要,我可以开始一个新问题。您需要使用
o
作为对象的构造函数。此对象将继承o
的原型
var o = function() { };
o.prototype.print = function( ) { console.log("hi") };
a = new o(); //a inherits prototype of constructor o
a.print();
类似地,由于o
本身是函数的一个实例,因此它继承了它的原型。请考虑<代码> var o=函数(){{} /代码>:
var o = new Function (""); //o inherits prototype of constructor Function
1.问题
我相信这是非常非常简单的,但是为什么下面的方法不起作用呢
var o = function() { };
o.prototype.print = function( ) { console.log("hi") };
o.print(); // console message: Object function o() { } has no method 'print'
o
是新对象的构造函数,必须创建新对象才能使用原型方法:
var x = new o();
x.print();
2.问题
为什么这也不起作用
var o = function() { };
o.prototype.print = function( ) { console.log("hi") };
var c = Object.create( o );
c.print();
因为Object.create
采用原型而非对象:
var o = function() { };
o.prototype.print = function( ) { console.log("hi") };
var c = Object.create( o.prototype );
c.print();
另见
- MDN:
- MDN:
函数MyObject(){};
var o=新的MyObject();
MyObject.prototype.print=function(){console.log(“hi”)};
o、 打印();